Silly question: how do you take the first N
elements from a julia Generator
?
For example, I have a generator that generates odd numbers:
julia> odds = (x for x in 1:2:typemax(Int))
Base.Generator{StepRange{Int64,Int64},var"##69#70"}(var"##69#70"(), 1:2:9223372036854775807)
How can I get the first 10 odd numbers? I tried things like this, all to no success:
julia> first(odds, 10)
ERROR: MethodError: no method matching first(::Base.Generator{StepRange{Int64,Int64},var"##69#70"}, ::Int64)
julia> head(odds, 10)
ERROR: UndefVarError: head not defined
julia> take!(odds, 10)
ERROR: MethodError: no method matching take!(::Base.Generator{StepRange{Int64,Int64},var"##69#70"}, ::Int64)
The methodswith
doesn't seem promising either:
julia> methodswith(Base.Generator)
[1] axes(g::Base.Generator) in Base at generator.jl:52
[2] collect(itr::Base.Generator) in Base at array.jl:615
[3] iterate(g::Base.Generator, s...) in Base at generator.jl:43
[4] length(g::Base.Generator) in Base at generator.jl:50
[5] ndims(g::Base.Generator) in Base at generator.jl:53
[6] size(g::Base.Generator) in Base at generator.jl:51
You can use Iterators.take
.
Try collect(Iterators.take(odds, 10))