Skip to content

Commit 0883b99

Browse files
stevengjstaticfloat
authored andcommitted
faster mapfoldl for tuples (#30471)
1 parent a254b52 commit 0883b99

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

base/tuple.jl

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -212,6 +212,18 @@ function map(f, t1::Any16, t2::Any16, ts::Any16...)
212212
(A...,)
213213
end
214214

215+
# mapafoldl, based on afold in operators.jl
216+
mapafoldl(F,op,a) = a
217+
mapafoldl(F,op,a,b) = op(a,F(b))
218+
mapafoldl(F,op,a,b,c...) = mapafoldl(F, op, op(a,F(b)), c...)
219+
function mapafoldl(F,op,a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,qs...)
220+
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))
221+
for x in qs; y = op(y,F(x)); end
222+
y
223+
end
224+
mapfoldl_impl(f, op, nt::NamedTuple{(:init,)}, t::Tuple) = mapafoldl(f, op, nt.init, t...)
225+
mapfoldl_impl(f, op, nt::NamedTuple{()}, t::Tuple) = mapafoldl(f, op, f(t[1]), tail(t)...)
226+
mapfoldl_impl(f, op, nt::NamedTuple{()}, t::Tuple{}) = mapreduce_empty_iter(f, op, t, IteratorEltype(t))
215227

216228
# type-stable padding
217229
fill_to_length(t::NTuple{N,Any}, val, ::Val{N}) where {N} = t

test/tuple.jl

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -237,6 +237,15 @@ end
237237
end
238238
end
239239

240+
@testset "mapfoldl" begin
241+
@test (((1=>2)=>3)=>4) == foldl(=>, (1,2,3,4)) ==
242+
mapfoldl(identity, =>, (1,2,3,4)) == mapfoldl(abs, =>, (-1,-2,-3,-4))
243+
@test mapfoldl(abs, =>, (-1,-2,-3,-4), init=-10) == ((((-10=>1)=>2)=>3)=>4)
244+
@test mapfoldl(abs, =>, (), init=-10) == -10
245+
@test mapfoldl(abs, Pair{Any,Any}, (-30:-1...,)) == mapfoldl(abs, Pair{Any,Any}, [-30:-1...,])
246+
@test_throws ArgumentError mapfoldl(abs, =>, ())
247+
end
248+
240249
@testset "comparison and hash" begin
241250
@test isequal((), ())
242251
@test isequal((1,2,3), (1,2,3))

0 commit comments

Comments
 (0)