functional-programming - 使用 Lazy.jl 在 Julia 中生成惰性范围

标签 functional-programming julia lazy-evaluation

试图扩展 Lazy.jl 中的示例之一,我遇到了评估不懒惰的问题。

README 使用了这个例子:

> esquares = @>> Lazy.range() map(x->x^2) filter(iseven);

> esquares[99]
39204

我试图通过允许将过滤器指定为参数来使其动态化,但它最终评估了一个无限列表:

> squares(filt) = @lazy @>> Lazy.range() map(x->x^2) filter(filt); 

> squares(iseven)

(4 16 36 64 100 144 196 256 324 400 484 576 676  ...   # this keeps printing until interrupting...)

我也试过:

> @lazy squares(iseven)  
(4 16 36 64 100 144 196 256 324 400 484 576 676  ...   # this also immediately returns the infinite list

最佳答案

显示惰性对象需要访问其内容(尽管当前的 show 方法是否应该更改是有争议的),这就是为什么 ;esquares 示例非常重要。

考虑到这一点,您的代码可以正常工作:

julia> squares(filt) = @lazy @>> Lazy.range() map(x->x^2) filter(filt) # you don't need the `@lazy` here I think
squares (generic function with 1 method)

julia> squares(iseven);

julia> squares(iseven)[99]
39204

julia> squares(isodd)[99]
38809

关于functional-programming - 使用 Lazy.jl 在 Julia 中生成惰性范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58479454/

相关文章:

lazy-evaluation - 按需求调用与按名称调用

Clojure。丢弃每个?

java - 在 Java 中将操作存储为数据的最佳方式是什么?

javascript - 使用函数式编程从 Google Places api 解析营业时间

performance - 在这种情况下,为什么 'all(itr) do' block 比 for 循环慢?

algorithm - 定点算法中的内存分配

serialization - Haskell中未定义长度列表的二进制序列化

scala - 猫效应 IO : Compose IO with Scala collections

java - 使用嵌套上限通配符时的不兼容类型

julia - 具有 "issetequal"的数组数组的唯一元素