Last active
December 4, 2018 20:23
-
-
Save mschauer/9eeef5f202e369bbc45b9b1190b225ab to your computer and use it in GitHub Desktop.
Stack filtered elements on top of iterator elements
This file contains hidden or 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
| 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