Skip to content

Instantly share code, notes, and snippets.

@Makman2
Created April 18, 2021 17:27
Show Gist options
  • Save Makman2/e582d1f257b7fffaa09da21d48809120 to your computer and use it in GitHub Desktop.
Save Makman2/e582d1f257b7fffaa09da21d48809120 to your computer and use it in GitHub Desktop.
Pairwise iteration recipe for Julia (analogous to Python's itertools recipe "pairwise")
import Base: iterate, length, eltype
struct Pairwise{IterType}
iter::IterType
end
function iterate(pairwise::Pairwise)
next = iterate(pairwise.iter)
return iterate(pairwise, next)
end
function iterate(pairwise::Pairwise, state)
previous, previous_original_state = state
next = iterate(pairwise.iter, previous_original_state)
return isnothing(next) ? nothing : ((previous, next[1]), next)
end
length(pairwise::Pairwise) = max(0, length(pairwise.iter) - 1)
eltype(::Type{Pairwise{IterType}}) where IterType = eltype(IterType)
pairwise(iter) = Pairwise(iter)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment