foldRight在无限的惰性结构上 [英] foldRight on infinite lazy structure

查看:58
本文介绍了foldRight在无限的惰性结构上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 http://en.wikipedia.org/wiki/Fold_(higher-order_function ),如果不需要评估完整列表,则可以对无限列表进行右折操作.这可以在haskell的操作中看到:

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]

对于流来说,这似乎在scala中效果不佳:

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

或在迭代器上:

Iterator.from(1).foldRight(Iterator.empty: Iterator[Int]){ (i, it) => 
  Iterator.single(i) ++ it
}.take(5)
// OutOfMemoryError: Java heap space

在Scala中是否有可行的解决方案来实现懒惰折叠?

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.

这篇关于foldRight在无限的惰性结构上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆