Will any functional language compiler/runtime reduce all chained iterations into one when applyable? From the programmer perspective we could optimize the functional code with such constructs as lazyness and streams but I am interested to know the other side of the story.
My functional example is written in Scala but please don’t limit your answers to that language.
Functional way:
// I assume the following line of code will go
// through the collection 3 times, one for creating it
// one for filtering it and one for summing it
val sum = (1L to 1000000L).filter(_ % 2 == 0).sum // => 250000500000
I would like the compiler to optimize to the imperative equivalent of:
/* One iteration only */
long sum, i;
for (i = 1L, sum = 0L; i <= 1000000L; i++) {
if (i % 2 == 0)
sum += i;
}
I posted two blog posts about exactly this topic a few years ago:
http://jnordenberg.blogspot.de/2010/03/scala-stream-fusion-and-specialization.html
http://jnordenberg.blogspot.de/2010/05/scala-stream-fusion-and-specialization.html
Note that the specialization and optimization done by the Scala compiler has improved quite a bit since then (probably in Hotspot as well), so the results might be even better today.