Skip to content

Commit eaf5a95

Browse files
committed
make zip for >2 arguments about 20x faster
I realized the only difference between Zip2 and general Zip should be a single `...` token.
1 parent 34dbb0f commit eaf5a95

File tree

1 file changed

+18
-28
lines changed

1 file changed

+18
-28
lines changed

base/iterator.jl

Lines changed: 18 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -19,39 +19,16 @@ eltype{I}(::Type{Enumerate{I}}) = (Int, eltype(I))
1919

2020
# zip
2121

22-
immutable Zip{I<:Tuple}
23-
itrs::I
24-
Zip(itrs) = new(itrs)
25-
end
26-
_mkZip{I}(itrs::I) = Zip{I}(itrs)
27-
Zip(itrs...) = _mkZip(itrs)
28-
zip(itrs...) = _mkZip(itrs)
29-
30-
length(z::Zip) = minimum(length, z.itrs)
31-
start(z::Zip) = map(start, z.itrs)
32-
function next(z::Zip, state)
33-
n = map(next, z.itrs, state)
34-
map(x->x[1], n), map(x->x[2], n)
35-
end
36-
done(z::Zip, state::()) = true
37-
function done(z::Zip, state)
38-
for i = 1:length(z.itrs)
39-
if done(z.itrs[i], state[i])
40-
return true
41-
end
42-
end
43-
return false
44-
end
22+
abstract AbstractZipIterator
4523

46-
eltype{I}(::Type{Zip{I}}) = map(eltype, I)
47-
48-
immutable Zip2{I1, I2}
24+
immutable Zip2{I1, I2} <: AbstractZipIterator
4925
a::I1
5026
b::I2
5127
end
28+
zip(a) = a
5229
zip(a, b) = Zip2(a, b)
53-
5430
length(z::Zip2) = min(length(z.a), length(z.b))
31+
eltype{I1,I2}(::Type{Zip2{I1,I2}}) = (eltype(I1), eltype(I2))
5532
start(z::Zip2) = (start(z.a), start(z.b))
5633
function next(z::Zip2, st)
5734
n1 = next(z.a,st[1])
@@ -60,7 +37,20 @@ function next(z::Zip2, st)
6037
end
6138
done(z::Zip2, st) = done(z.a,st[1]) | done(z.b,st[2])
6239

63-
eltype{I1,I2}(::Type{Zip2{I1,I2}}) = (eltype(I1), eltype(I2))
40+
immutable Zip{I, Z<:AbstractZipIterator} <: AbstractZipIterator
41+
a::I
42+
z::Z
43+
end
44+
zip(a, b, c...) = Zip(a, zip(b, c...))
45+
length(z::Zip) = min(length(z.a), length(z.z))
46+
eltype{I,Z}(::Type{Zip{I,Z}}) = tuple(eltype(I), eltype(Z)...)
47+
start(z::Zip) = tuple(start(z.a), start(z.z))
48+
function next(z::Zip, st)
49+
n1 = next(z.a, st[1])
50+
n2 = next(z.z, st[2])
51+
(tuple(n1[1], n2[1]...), (n1[2], n2[2]))
52+
end
53+
done(z::Zip, st) = done(z.a,st[1]) | done(z.z,st[2])
6454

6555
# filter
6656

0 commit comments

Comments
 (0)