scala: adding a method to List?

后端 未结 3 1719
深忆病人
深忆病人 2021-01-13 11:55

I was wondering how to go about adding a \'partitionCount\' method to Lists, e.g.: (not tested, shamelessly based on List.scala):

Do I have to create my own sub-clas

3条回答
  •  不思量自难忘°
    2021-01-13 12:36

    Easy Angel is right, but the method seems pretty useless. You have already count in order to get the number of "positives", and of course the number of "negatives" is size minus count.

    However, to contribute something positive, here 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)}
    

提交回复
热议问题