Skip to content

Instantly share code, notes, and snippets.

@hessammehr
Created October 22, 2018 00:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hessammehr/8ae905b92435f8a0aeb8fc9f62f33734 to your computer and use it in GitHub Desktop.
Save hessammehr/8ae905b92435f8a0aeb8fc9f62f33734 to your computer and use it in GitHub Desktop.
Efficient flatten
function Base.iterate(mf::MyFlatten{I,T}, state=nothing) where {I,T}
if state===nothing
val = iterate(mf.a)
val === nothing && return nothing
itr, s = val
res = iterate(itr)
else
itr, s, inner_s = state
res = iterate(itr, inner_s)
end
if res === nothing
res2 = iterate(mf.a, s)
res2 === nothing && return nothing
itr, s = res2
res3 = iterate(itr)
res3 === nothing && return nothing
return res3[1], (itr, s, res3[2])
else
return res[1], (itr, s, res[2])
end
end
Base.eltype(mf :: MyFlatten{I,T}) where {I,T} = T
Base.IteratorSize(::T) where T<:MyFlatten = Base.SizeUnknown()
struct MyFlatten{I,T}
a::I
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment