Skip to content

Commit 3522661

Browse files
authored
Add specialization of foreach for tuples (#31901)
1 parent a32a066 commit 3522661

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

base/tuple.jl

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -551,3 +551,6 @@ end
551551
Returns an empty tuple, `()`.
552552
"""
553553
empty(@nospecialize x::Tuple) = ()
554+
555+
foreach(f, itr::Tuple) = foldl((_, x) -> (f(x); nothing), itr, init=nothing)
556+
foreach(f, itrs::Tuple...) = foldl((_, xs) -> (f(xs...); nothing), zip(itrs...), init=nothing)

test/tuple.jl

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -277,6 +277,42 @@ end
277277
end
278278
end
279279

280+
@testset "foreach" begin
281+
longtuple = ntuple(identity, 20)
282+
283+
@testset "1 argument" begin
284+
foo(x) = push!(a, x)
285+
286+
a = []
287+
foreach(foo, ())
288+
@test a == []
289+
290+
a = []
291+
foreach(foo, (1,))
292+
@test a == [1]
293+
294+
a = []
295+
foreach(foo, longtuple)
296+
@test a == [longtuple...]
297+
end
298+
299+
@testset "n arguments" begin
300+
foo(x, y) = push!(a, (x, y))
301+
302+
a = []
303+
foreach(foo, (), ())
304+
@test a == []
305+
306+
a = []
307+
foreach(foo, (1,), (2,))
308+
@test a == [(1, 2)]
309+
310+
a = []
311+
foreach(foo, longtuple, longtuple)
312+
@test a == [(x, x) for x in longtuple]
313+
end
314+
end
315+
280316
@testset "mapfoldl" begin
281317
@test (((1=>2)=>3)=>4) == foldl(=>, (1,2,3,4)) ==
282318
mapfoldl(identity, =>, (1,2,3,4)) == mapfoldl(abs, =>, (-1,-2,-3,-4))

0 commit comments

Comments
 (0)