Iterator with previous and current elements

I am wondering if it is possible to iterate over pairs of the previous and the current element in an iterable collection. Eg to implement

function pairs_sum(s)
    result = []
    state = start(s)
    while !done(s, state)
        (i, next_state) = next(s, state)
        push!(result, state+next_state)
        state = next_state
    end
    result
end

as

pairs_sum(s) = [sum(e) for e in (magic here)]

with seeing each element only once, so

pairs_sum(s) = [sum(e) for e in zip(s, drop(s,1))]

doesn’t count.

I think Base.(Iterators.)partition does what you ask.
The extra Iterators middle part is if you are on julia 0.6

1 Like