Building Generators in Julia

Initially, we establish some constructions using struct and making sure Julia knows how to iterate over this object by defining length, eltype, and iterate.

struct OneTo{T}
    val::T
end

OneTo(N) = OneTo{Int}(N)

Base.length(S::OneTo) = S.val
Base.eltype(::Type{OneTo}) = Int

function Base.iterate(S::OneTo, state=1)
    state > S.val ? nothing : (state, state+1)
end

We can then wrap it in a function for easy instantiation of the generator, using the parentheses instead of square braces to designate generator rather than list comprehension.

oneto(N) = (x for x in OneTo(N))

for k in oneto(10)
    println(k)
end