Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

RFC: add foreach function #13774

Merged
merged 2 commits into from
Oct 26, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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