Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

reverse(zip(its...)) now checks lengths of constituent iterators for equality #50435

Merged
merged 3 commits into from
Oct 26, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 22 additions & 1 deletion base/iterators.jl
Original file line number Diff line number Diff line change
Expand Up @@ -387,6 +387,22 @@ function _zip_min_length(is)
end
end
_zip_min_length(is::Tuple{}) = nothing

# For a collection of iterators `is`, returns a tuple (b, n), where
# `b` is true when every component of `is` has a statically-known finite
# length and all such lengths are equal. Otherwise, `b` is false.
# `n` is an implementation detail, and will be the `length` of the first
# iterator if it is statically-known and finite. Otherwise, `n` is `nothing`.
function _zip_lengths_finite_equal(is)
i = is[1]
if IteratorSize(i) isa Union{IsInfinite, SizeUnknown}
return (false, nothing)
else
b, n = _zip_lengths_finite_equal(tail(is))
return (b && (n === nothing || n == length(i)), length(i))
end
end
_zip_lengths_finite_equal(is::Tuple{}) = (true, nothing)
adienes marked this conversation as resolved.
Show resolved Hide resolved
size(z::Zip) = _promote_tuple_shape(Base.map(size, z.is)...)
axes(z::Zip) = _promote_tuple_shape(Base.map(axes, z.is)...)
_promote_tuple_shape((a,)::Tuple{OneTo}, (b,)::Tuple{OneTo}) = (intersect(a, b),)
Expand Down Expand Up @@ -468,8 +484,13 @@ zip_iteratoreltype() = HasEltype()
zip_iteratoreltype(a) = a
zip_iteratoreltype(a, tail...) = and_iteratoreltype(a, zip_iteratoreltype(tail...))

reverse(z::Zip) = Zip(Base.map(reverse, z.is)) # n.b. we assume all iterators are the same length
last(z::Zip) = getindex.(z.is, minimum(Base.map(lastindex, z.is)))
function reverse(z::Zip)
if !first(_zip_lengths_finite_equal(z.is))
throw(ArgumentError("Cannot reverse zipped iterators of unknown, infinite, or unequal lengths"))
end
Zip(Base.map(reverse, z.is))
end

# filter

Expand Down
4 changes: 4 additions & 0 deletions test/iterators.jl
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,10 @@ using Dates: Date, Day
# issue #4718
@test collect(Iterators.filter(x->x[1], zip([true, false, true, false],"abcd"))) == [(true,'a'),(true,'c')]

# issue #45085
@test_throws ArgumentError Iterators.reverse(zip("abc", "abcd"))
@test_throws ArgumentError Iterators.reverse(zip("abc", Iterators.cycle("ab")))

let z = zip(1:2)
@test size(z) == (2,)
@test collect(z) == [(1,), (2,)]
Expand Down