Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
851 views
in Technique[技术] by (71.8m points)

scala - Difference between fold and foldLeft or foldRight?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Short answer:

foldRight associates to the right. I.e. elements will be accumulated in right-to-left order:

List(a,b,c).foldRight(z)(f) = f(a, f(b, f(c, z)))

foldLeft associates to the left. I.e. an accumulator will be initialized and elements will be added to the accumulator in left-to-right order:

List(a,b,c).foldLeft(z)(f) = f(f(f(z, a), b), c)

fold is associative in that the order in which the elements are added together is not defined. I.e. the arguments to fold form a monoid.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...