Skip to content

Instantly share code, notes, and snippets.

@mschauer
Last active December 4, 2018 20:23
Show Gist options
  • Select an option

  • Save mschauer/9eeef5f202e369bbc45b9b1190b225ab to your computer and use it in GitHub Desktop.

Select an option

Save mschauer/9eeef5f202e369bbc45b9b1190b225ab to your computer and use it in GitHub Desktop.
Stack filtered elements on top of iterator elements
struct Stack{I,F}
iter::I
f::F
end
import Base.iterate
function iterate(S::Stack)
ϕ = iterate(S.iter)
ϕ === nothing && return nothing
x, state = ϕ
while !S.f(x)
ϕ = iterate(S.iter, state)
ϕ === nothing && return nothing
x, state = ϕ
end
iterate(S, (x, state))
end
function iterate(S::Stack, (header, state))
ϕ = iterate(S.iter, state)
ϕ === nothing && return nothing
x, state = ϕ
while S.f(x)
header = x
ϕ = iterate(S.iter, state)
ϕ === nothing && return nothing
x, state = ϕ
end
(header, x), (header, state)
end
Base.IteratorSize(::Stack) = Base.SizeUnknown()
S = Stack(1:20, x -> x in [3, 10, 15])
Base.eltype(S::Stack) = Tuple{eltype(S.iter),eltype(S.iter)}
Base.IteratorEltype(::Stack{I}) where {I} = Base.IteratorEltype(I)
iterate(S)
collect(S)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment