Lazy Range Generation in Julia with Lazy.jl

Viewed 253

In trying to extend one of the examples from Lazy.jl, I encountered an issue where the evaluation isn't lazy.

The README uses this example:

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

> esquares[99]
39204

I tried to make it dynamic by allowing one to specify the filter as an argument, but it ends up evaluating an infinite list:

> 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...)

I also tried:

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

Displaying a lazy object needs to access its contents (although it's debatable whether the current show methods should be changed or not), which is why the ; in the esquares example is so important.

Your code works just fine with that in mind:

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
Related