NOTE: I am on Scala 2.8—can that be a problem?
Why can't I use the fold
function the same way as foldLeft
or foldRight
?
In the Set scaladoc it says that:
The result of folding may only be a supertype of this parallel collection's type parameter T
.
But I see no type parameter T
in the function signature:
def fold [A1 >: A] (z: A1)(op: (A1, A1) ? A1): A1
What is the difference between the foldLeft-Right
and fold
, and how do I use the latter?
EDIT: For example how would I write a fold to add all elements in a list? With foldLeft
it would be:
val foo = List(1, 2, 3)
foo.foldLeft(0)(_ + _)
// now try fold:
foo.fold(0)(_ + _)
>:7: error: value fold is not a member of List[Int]
foo.fold(0)(_ + _)
^
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…