Skip to content

Commit

Permalink
Merge pull request #13774 from JuliaLang/jb/foreach
Browse files Browse the repository at this point in the history
RFC: add `foreach` function
  • Loading branch information
JeffBezanson committed Oct 26, 2015
2 parents aa1076d + 71fc3b3 commit 4b2bc22
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 0 deletions.
3 changes: 3 additions & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,9 @@ Library improvements
appropriate. The `sparsevec` function returns a one-dimensional sparse
vector instead of a one-column sparse matrix. ([#13440])

* New `foreach` function for calling a function on every element of a collection when
the results are not needed.

Deprecated or removed
---------------------

Expand Down
12 changes: 12 additions & 0 deletions base/abstractarray.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1137,6 +1137,18 @@ end

## iteration utilities ##

doc"""
foreach(f, c...) -> Void
Call function `f` on each element of iterable `c`.
For multiple iterable arguments, `f` is called elementwise.
`foreach` should be used instead of `map` when the results of `f` are not
needed, for example in `foreach(println, array)`.
"""
foreach(f) = (f(); nothing)
foreach(f, itr) = (for x in itr; f(x); end; nothing)
foreach(f, itrs...) = (for z in zip(itrs...); f(z...); end; nothing)

# generic map on any iterator
function map(f, iters...)
result = []
Expand Down
1 change: 1 addition & 0 deletions base/exports.jl
Original file line number Diff line number Diff line change
Expand Up @@ -753,6 +753,7 @@ export
filter,
foldl,
foldr,
foreach,
get,
get!,
getindex,
Expand Down
13 changes: 13 additions & 0 deletions test/functional.jl
Original file line number Diff line number Diff line change
Expand Up @@ -138,3 +138,16 @@ let i = 0
i <= 10 || break
end
end

# foreach
let
a = []
foreach(()->push!(a,0))
@test a == [0]
a = []
foreach(x->push!(a,x), [1,5,10])
@test a == [1,5,10]
a = []
foreach((args...)->push!(a,args), [2,4,6], [10,20,30])
@test a == [(2,10),(4,20),(6,30)]
end

0 comments on commit 4b2bc22

Please sign in to comment.