lembark (6) [Avatar] Offline
#1
I'm not really seeing how foldLeft differs from reduce (with the possible change that the accumulated value is passed vs. stored internally). Be nice to see if either (a) fL is a synonym for "reduce" or (b) what really makes it different usen used with FP.
aslam.khan (50) [Avatar] Offline
#2
Re: Be interesting to see how foldLeft differs from reduce (p.85+)
That is a very good question. The way that I introduced it, reduce is a special form of fold. I wanted to avoid the subtle difference at this point, but I think I will have to include it since it is causing some confusion.

So, in advance of the correction, and to clear the confusion for you...

A fold can take a list of any type, perform an operation on it, and output something of a completely different type. For example, take a list of integers and output a List of string values of the integers:
[pre]
List(1,2,3,4,5).foldLeft(List[String]()) { (a, b) => b.toString :: a }
[/pre]

A reduce, on the other hand, will behave just like a fold but is constrained in producing an output of the same type as the that of the input collection (or a supertype thereof).

[pre]
List(1,2,3,4,5).reduceLeft { (a, b) => a + b }
[/pre]