Scala: adding a method to a list?

I was wondering how to proceed with adding the "partitionCount" method to lists, for example: (not tested, shamelessly based on List.scala):

Do I need to create my own subclass and implicit type converter?

(My initial attempt had a lot of problems, so here is one of them based on @Easy answer):

class MyRichList[A](targetList: List[A]) {
  def partitionCount(p: A => Boolean): (Int, Int) = {
    var btrue = 0
    var bfalse = 0
    var these = targetList
    while (!these.isEmpty) {
      if (p(these.head)) { btrue += 1 }  else { bfalse += 1 }
      these = these.tail
    }
    (btrue, bfalse)
  }
}

and here is a slightly more general version that is good for Seq [...]:

implicit def seqToRichSeq[T](s: Seq[T]) = new MyRichSeq(s)

class MyRichList[A](targetList: List[A]) {
  def partitionCount(p: A => Boolean): (Int, Int) = {
    var btrue = 0
    var bfalse = 0
    var these = targetList
    while (!these.isEmpty) {
      if (p(these.head)) { btrue += 1 }  else { bfalse += 1 }
      these = these.tail
    }
    (btrue, bfalse)
  }
}
+5
source share
3 answers

You can use implicit conversion as follows:

implicit def listToMyRichList[T](l: List[T]) = new MyRichList(l)

class MyRichList[T](targetList: List[T]) {
    def partitionCount(p: T => Boolean): (Int, Int) = ...
}

and instead thisyou need to use targetList. You do not need to expand List. In this example, I am creating a simple wrapper MyRichListthat will be used implicitly.

, Traversable, , List s:

implicit def listToMyRichTraversable[T](l: Traversable[T]) = new MyRichTraversable(l)

class MyRichTraversable[T](target: Traversable[T]) {
    def partitionCount(p: T => Boolean): (Int, Int) = ...
}

, , . , import ( , ).

+8

Easy Angel, :

implicit def listTorichList[A](input: List[A]) = new RichList(input)

class RichList[A](val source: List[A]) {

    def partitionCount(p: A => Boolean): (Int, Int) = {
        val partitions = source partition(p)
        (partitions._1.size, partitions._2.size)
    }
}

, partitionCount partinion. :

val list = List(1, 2, 3, 5, 7, 11)
val (odd, even) = list partitionCount {_ % 2 != 0}

, , implicit list2richList ( , , implicit).

val (odd, even) = list2richList(list) partitionCount {_ % 2 != 0}
+3

The light angel is right, but the method seems pretty worthless. You already have countto get the number of "positives", and, of course, the number of "negatives" sizeminus count.

However, to make something positive, here is a more functional version of your original method:

def partitionCount[A](iter: Traversable[A], p: A => Boolean): (Int, Int) =
   iter.foldLeft ((0,0)) { ((x,y), a) => if (p(a)) (x + 1,y) else (x, y + 1)}
+1
source

All Articles