According to http://en.wikipedia.org/wiki/Fold_(higher-order_function), a right fold can operate on infinite lists if the full list does not have to be evaluated. This can be seen in action in haskell:
Prelude> take 5 (foldr (:) [] [1 ..])
[1,2,3,4,5]
This does not seem to work well in scala for streams:
Stream.from(1).foldRight(Stream.empty[Int])( (i, s) => i #:: s).take(5)
// StackOverflowError
or on iterators:
Iterator.from(1).foldRight(Iterator.empty: Iterator[Int]){ (i, it) =>
Iterator.single(i) ++ it
}.take(5)
// OutOfMemoryError: Java heap space
Is there a practical solution to achieve a lazy fold right in Scala?
This article makes the same observation, and suggests a lazy solution using scalaz. Credit to the author, and Tony Morris.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With