julia

Is there a lazy and iterative `map` in Julia?


The map function seems eager, e.g.

map(x->x+1, 1:3) gives one [2,3,4].

I want to find a lazy and iterative version of map so that the values are not generated all at once, so I can just get values one by one from the result of the map?


Solution

  • You can use Base.Generator for this, e.g. in your case:

    julia> g = (x + 1 for x in 1:3)
    Base.Generator{UnitRange{Int64},getfield(Main, Symbol("##5#6"))}(getfield(Main, Symbol("##5#6"))(), 1:3)
    
    julia> collect(g)
    3-element Array{Int64,1}:
     2
     3
     4