Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

foldRight on infinite lazy structure

Tags:

scala

fold

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?

like image 375
huynhjl Avatar asked Oct 20 '11 02:10

huynhjl


Video Answer


1 Answers

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

like image 51
Tim Avatar answered Oct 16 '22 14:10

Tim