Skip to content

Commit

Permalink
make map on tuples accept different lengths (#49336)
Browse files Browse the repository at this point in the history
fix #49299, fix #42216
  • Loading branch information
JeffBezanson authored May 4, 2023
1 parent daea3c3 commit bb31772
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 6 deletions.
10 changes: 8 additions & 2 deletions base/tuple.jl
Original file line number Diff line number Diff line change
Expand Up @@ -313,14 +313,16 @@ function map(f, t::Any32)
end
# 2 argument function
map(f, t::Tuple{}, s::Tuple{}) = ()
map(f, t::Tuple, s::Tuple{}) = ()
map(f, t::Tuple{}, s::Tuple) = ()
map(f, t::Tuple{Any,}, s::Tuple{Any,}) = (@inline; (f(t[1],s[1]),))
map(f, t::Tuple{Any,Any}, s::Tuple{Any,Any}) = (@inline; (f(t[1],s[1]), f(t[2],s[2])))
function map(f, t::Tuple, s::Tuple)
@inline
(f(t[1],s[1]), map(f, tail(t), tail(s))...)
end
function map(f, t::Any32, s::Any32)
n = length(t)
n = min(length(t), length(s))
A = Vector{Any}(undef, n)
for i = 1:n
A[i] = f(t[i], s[i])
Expand All @@ -331,12 +333,16 @@ end
heads(ts::Tuple...) = map(t -> t[1], ts)
tails(ts::Tuple...) = map(tail, ts)
map(f, ::Tuple{}...) = ()
anyempty(x::Tuple{}, xs...) = true
anyempty(x::Tuple, xs...) = anyempty(xs...)
anyempty() = false
function map(f, t1::Tuple, t2::Tuple, ts::Tuple...)
@inline
anyempty(t1, t2, ts...) && return ()
(f(heads(t1, t2, ts...)...), map(f, tails(t1, t2, ts...)...)...)
end
function map(f, t1::Any32, t2::Any32, ts::Any32...)
n = length(t1)
n = min(length(t1), length(t2), minimum(length, ts))
A = Vector{Any}(undef, n)
for i = 1:n
A[i] = f(t1[i], t2[i], map(t -> t[i], ts)...)
Expand Down
13 changes: 9 additions & 4 deletions test/tuple.jl
Original file line number Diff line number Diff line change
Expand Up @@ -265,8 +265,10 @@ end
@test map(foo, (1,2,3,4), (1,2,3,4)) === (2,4,6,8)
@test map(foo, longtuple, longtuple) === ntuple(i->2i,20)
@test map(foo, vlongtuple, vlongtuple) === ntuple(i->2i,33)
@test_throws BoundsError map(foo, (), (1,))
@test_throws BoundsError map(foo, (1,), ())
@test map(foo, longtuple, vlongtuple) === ntuple(i->2i,20)
@test map(foo, vlongtuple, longtuple) === ntuple(i->2i,20)
@test map(foo, (), (1,)) === ()
@test map(foo, (1,), ()) === ()
end

@testset "n arguments" begin
Expand All @@ -276,8 +278,11 @@ end
@test map(foo, (1,2,3,4), (1,2,3,4), (1,2,3,4)) === (3,6,9,12)
@test map(foo, longtuple, longtuple, longtuple) === ntuple(i->3i,20)
@test map(foo, vlongtuple, vlongtuple, vlongtuple) === ntuple(i->3i,33)
@test_throws BoundsError map(foo, (), (1,), (1,))
@test_throws BoundsError map(foo, (1,), (1,), ())
@test map(foo, vlongtuple, longtuple, longtuple) === ntuple(i->3i,20)
@test map(foo, longtuple, vlongtuple, longtuple) === ntuple(i->3i,20)
@test map(foo, longtuple, vlongtuple, vlongtuple) === ntuple(i->3i,20)
@test map(foo, (), (1,), (1,)) === ()
@test map(foo, (1,), (1,), ()) === ()
end
end

Expand Down

0 comments on commit bb31772

Please sign in to comment.