Skip to content

Commit

Permalink
faster mapfoldl for tuples (#30471)
Browse files Browse the repository at this point in the history
(cherry picked from commit 6dc205a)
  • Loading branch information
stevengj authored and KristofferC committed Dec 30, 2018
1 parent ded25d3 commit 0195be0
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 0 deletions.
12 changes: 12 additions & 0 deletions base/tuple.jl
Original file line number Diff line number Diff line change
Expand Up @@ -209,6 +209,18 @@ function map(f, t1::Any16, t2::Any16, ts::Any16...)
(A...,)
end

# mapafoldl, based on afold in operators.jl
mapafoldl(F,op,a) = a
mapafoldl(F,op,a,b) = op(a,F(b))
mapafoldl(F,op,a,b,c...) = mapafoldl(F, op, op(a,F(b)), c...)
function mapafoldl(F,op,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,qs...)
y = op(op(op(op(op(op(op(op(op(op(op(op(op(op(op(a,F(b)),F(c)),F(d)),F(e)),F(f)),F(g)),F(h)),F(i)),F(j)),F(k)),F(l)),F(m)),F(n)),F(o)),F(p))
for x in qs; y = op(y,F(x)); end
y
end
mapfoldl_impl(f, op, nt::NamedTuple{(:init,)}, t::Tuple) = mapafoldl(f, op, nt.init, t...)
mapfoldl_impl(f, op, nt::NamedTuple{()}, t::Tuple) = mapafoldl(f, op, f(t[1]), tail(t)...)
mapfoldl_impl(f, op, nt::NamedTuple{()}, t::Tuple{}) = mapreduce_empty_iter(f, op, t, IteratorEltype(t))

# type-stable padding
fill_to_length(t::NTuple{N,Any}, val, ::Val{N}) where {N} = t
Expand Down
9 changes: 9 additions & 0 deletions test/tuple.jl
Original file line number Diff line number Diff line change
Expand Up @@ -237,6 +237,15 @@ end
end
end

@testset "mapfoldl" begin
@test (((1=>2)=>3)=>4) == foldl(=>, (1,2,3,4)) ==
mapfoldl(identity, =>, (1,2,3,4)) == mapfoldl(abs, =>, (-1,-2,-3,-4))
@test mapfoldl(abs, =>, (-1,-2,-3,-4), init=-10) == ((((-10=>1)=>2)=>3)=>4)
@test mapfoldl(abs, =>, (), init=-10) == -10
@test mapfoldl(abs, Pair{Any,Any}, (-30:-1...,)) == mapfoldl(abs, Pair{Any,Any}, [-30:-1...,])
@test_throws ArgumentError mapfoldl(abs, =>, ())
end

@testset "comparison and hash" begin
@test isequal((), ())
@test isequal((1,2,3), (1,2,3))
Expand Down

0 comments on commit 0195be0

Please sign in to comment.