foldRight on infinite lazy structure

一世执手 提交于 2019-11-29 06:11:04

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/7830471/foldright-on-infinite-lazy-structure

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!