Rajkumar Goel wrote:

Can anyone give me a insight to folding list in Scala.


Hello Raj,

Sometimes there are situations where it is necessary to somehow combine or
examine every element in a collection, producing a single value as a result.
This technique is known as folding.

Folding a collection is literally the process of looking at each element in
addition to a current accumulator and returning some value.


Consider this code:


val nums = List(1, 2, 3, 4, 5)


val sum = nums.foldLeft(0) {
 (total, n) => total + n
}


this is a loop, just like foreach.  For each element in the list (starting
from the left), the foldLeft method will call the anonymous method we passed
to it, providing both the current element, as well as the total accumulated
from the previous call.  Since there was no previous call when the first
element is processed, we must specify an initial value for total ( in this
case, 0).  Literally, the above can be flattened into the following:

val sum = 0 + 1 + 2 + 3 + 4 + 5


val nums = List(1, 2, 3, 4, 5)
( 0 /: nums ) { _+_ }



PS: I'm unable to do folding stuff in eclipse.
If any one got, please post the method...





-- 
Cheers,
Pratik K Anand


[Non-text portions of this message have been removed]

Reply via email to