Skip to content

Commit 4b2bc22

Browse files
committed
Merge pull request #13774 from JuliaLang/jb/foreach
RFC: add `foreach` function
2 parents aa1076d + 71fc3b3 commit 4b2bc22

File tree

4 files changed

+29
-0
lines changed

4 files changed

+29
-0
lines changed

NEWS.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,9 @@ Library improvements
6161
appropriate. The `sparsevec` function returns a one-dimensional sparse
6262
vector instead of a one-column sparse matrix. ([#13440])
6363

64+
* New `foreach` function for calling a function on every element of a collection when
65+
the results are not needed.
66+
6467
Deprecated or removed
6568
---------------------
6669

base/abstractarray.jl

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1137,6 +1137,18 @@ end
11371137

11381138
## iteration utilities ##
11391139

1140+
doc"""
1141+
foreach(f, c...) -> Void
1142+
1143+
Call function `f` on each element of iterable `c`.
1144+
For multiple iterable arguments, `f` is called elementwise.
1145+
`foreach` should be used instead of `map` when the results of `f` are not
1146+
needed, for example in `foreach(println, array)`.
1147+
"""
1148+
foreach(f) = (f(); nothing)
1149+
foreach(f, itr) = (for x in itr; f(x); end; nothing)
1150+
foreach(f, itrs...) = (for z in zip(itrs...); f(z...); end; nothing)
1151+
11401152
# generic map on any iterator
11411153
function map(f, iters...)
11421154
result = []

base/exports.jl

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -753,6 +753,7 @@ export
753753
filter,
754754
foldl,
755755
foldr,
756+
foreach,
756757
get,
757758
get!,
758759
getindex,

test/functional.jl

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -138,3 +138,16 @@ let i = 0
138138
i <= 10 || break
139139
end
140140
end
141+
142+
# foreach
143+
let
144+
a = []
145+
foreach(()->push!(a,0))
146+
@test a == [0]
147+
a = []
148+
foreach(x->push!(a,x), [1,5,10])
149+
@test a == [1,5,10]
150+
a = []
151+
foreach((args...)->push!(a,args), [2,4,6], [10,20,30])
152+
@test a == [(2,10),(4,20),(6,30)]
153+
end

0 commit comments

Comments
 (0)