Creating Generators

Thanks Chris.

I think my attempt above does use the iterator interface - happy that I’ve used the best method to create one.

After seeing your response and thinking about this a bit more, my main issue was probably more around the fact that I had to create two generators to achieve what I wanted as there was a nested while under the for.

I ended up working out that you can create a type for the state variable that has an accumulator, which works (see code below), but I’m still wondering if this approach is reasonable or what other people do?

Also, by “more complicated generator”, I really meant anything that couldn’t be easily achieved in something like a list comprehension.

type Generator
    s::String
end

type State
    i::Int64
    index_bit::Int8
    acc::Int8
end

Base.start(x::Generator) = State(1, 0, 0)
Base.done(x::Generator, state::State) = (length(x.s), 7) == (state.i, state.index_bit)

function Base.next(x::Generator, state::State)
    if state.index_bit == 0
        state = State(state.i, state.index_bit + 1, Int8(x.s[state.i]))
    elseif state.index_bit == 7
        state = State(state.i + 1, 1, Int8(x.s[state.i + 1]))
    else
        state = State(state.i, state.index_bit + 1, state.acc >> 1)
    end
    println("$(state.acc & 1) | $state")
    state.acc & 1, state
end
    
s = "here"
for (i, x) in enumerate(Generator(s)) end