Tag Archives: foldLeft

Lists and folding in Scala

James Iry pointed out that I could have used a fold left in my solution to the first ProjectEuler problem. Ah, now I remember reading about folds!  So, I went back and looked at it.  Right he is, of course.

Here's his solution:

val nums = 3 until 1000

val somenums = nums filter (x => (x % 3 == 0 || x % 5 ==0))

val sum = somenums reduceLeft {(x:Int,y:Int) => x + y}

println(sum)

Equivalently:

val sum = somenums.foldLeft(0)(_+_)

And more obscurely:

(0/:somenums)(_+_) 

I came across a great blog post describing all of this.   

I have to admit that I'm not enamoured with the last example above (the (0/:somenums)(_+_).  But, the (_+_) is at least fun to type since it's all done with the right hand while the shift key is depressed with the left!   

Anyhow, I'm encouraged to learn more about folding lists now!   Many thanks to both James Iry and Joel Neely for their suggestions and support (and to Ricky Clarkson for his fabulous blog post on folding).