Skip to content

Commit c640ded

Browse files
add chain
1 parent 7805870 commit c640ded

File tree

1 file changed

+61
-0
lines changed

1 file changed

+61
-0
lines changed

src/utils.jl

Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -111,3 +111,64 @@ function recursive_mean{T<:AbstractArray}(matarr::Matrix{T},region=0)
111111
return recursive_mean(matarr',1)
112112
end
113113
end
114+
115+
116+
# From Iterators.jl. Moved here since Iterators.jl is not precompile safe anymore.
117+
118+
# Concatenate the output of n iterators
119+
immutable Chain{T<:Tuple}
120+
xss::T
121+
end
122+
123+
# iteratorsize method defined at bottom because of how @generated functions work in 0.6 now
124+
125+
"""
126+
chain(xs...)
127+
128+
Iterate through any number of iterators in sequence.
129+
```jldoctest
130+
julia> for i in chain(1:3, ['a', 'b', 'c'])
131+
@show i
132+
end
133+
i = 1
134+
i = 2
135+
i = 3
136+
i = 'a'
137+
i = 'b'
138+
i = 'c'
139+
```
140+
"""
141+
chain(xss...) = Chain(xss)
142+
143+
Base.length(it::Chain{Tuple{}}) = 0
144+
Base.length(it::Chain) = sum(length, it.xss)
145+
146+
Base.eltype{T}(::Type{Chain{T}}) = typejoin([eltype(t) for t in T.parameters]...)
147+
148+
function Base.start(it::Chain)
149+
i = 1
150+
xs_state = nothing
151+
while i <= length(it.xss)
152+
xs_state = start(it.xss[i])
153+
if !done(it.xss[i], xs_state)
154+
break
155+
end
156+
i += 1
157+
end
158+
return i, xs_state
159+
end
160+
161+
function Base.next(it::Chain, state)
162+
i, xs_state = state
163+
v, xs_state = next(it.xss[i], xs_state)
164+
while done(it.xss[i], xs_state)
165+
i += 1
166+
if i > length(it.xss)
167+
break
168+
end
169+
xs_state = start(it.xss[i])
170+
end
171+
return v, (i, xs_state)
172+
end
173+
174+
Base.done(it::Chain, state) = state[1] > length(it.xss)

0 commit comments

Comments
 (0)