【问题标题】:Lazy Range Generation in Julia with Lazy.jl使用 Lazy.jl 在 Julia 中生成惰性范围
【发布时间】:2019-10-21 03:30:14
【问题描述】:

在尝试扩展 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

【问题讨论】:

    标签: functional-programming julia lazy-evaluation


    【解决方案1】:

    显示一个惰性对象需要访问它的内容(尽管是否应该更改当前的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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-08-11
      • 2011-02-08
      • 2015-11-21
      • 2013-01-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多