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

Ale*_*lec 3 functional-programming lazy-evaluation julia

在尝试扩展Lazy.jl 中的一个示例时,我遇到了评估不是惰性的问题。

README使用这个例子:

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

> esquares[99]
39204
Run Code Online (Sandbox Code Playgroud)

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

> 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...)
Run Code Online (Sandbox Code Playgroud)

我也试过:

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

pfi*_*seb 5

显示一个懒惰的对象需要访问其内容(尽管它的争议是否当前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
Run Code Online (Sandbox Code Playgroud)