Created
April 18, 2021 17:27
-
-
Save Makman2/e582d1f257b7fffaa09da21d48809120 to your computer and use it in GitHub Desktop.
Pairwise iteration recipe for Julia (analogous to Python's itertools recipe "pairwise")
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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