19

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?

huynhjl
  • 41,520
  • 14
  • 105
  • 158

1 Answers1

18

This article makes the same observation, and suggests a lazy solution using scalaz. Credit to the author, and Tony Morris.

Tim
  • 766
  • 1
  • 7
  • 13
  • Thank you. I can use scalaz. It works for `Stream`. Iterators seem more tricky... – huynhjl Oct 20 '11 at 14:05
  • 7
    The article doesn't suggest using scalaz at all, but gives a solution in pure scala which it says was inspired by scalaz's implementation: `def foldr[A, B]( combine: (A, =>B) => B, base: B )(xs: Stream[A]): B = if (xs.isEmpty) base else combine(xs.head, foldr(combine, base)(xs.tail))` – Luigi Plinge Oct 21 '11 at 00:09