How do you forEach in Elixir? In JavaScript (and most languages have an equivalent), I can iterate through the various items in a list and do something with side effects like outputting to the console.
[1,2,3].forEach(function(num) {
console.log(num);
});
//=> 1
//=> 2
//=> 3
Is there an equivalent in elixir?
Iterating through a collection is most often handled with the Enum
module. Enum.each/2
is what you're looking for if you want to generate side effects.
Enum.each/2
function takes two arguments: your collection and a function to run on every member of the collection.
Like so:
iex(3)> Enum.each([1, 2, 3], fn x -> IO.puts x end)
1
2
3
:ok
I wrote a blog post about this recently which goes into more details. The post is a comparison between Elixir and Ruby, but the same exact logic applies to JavaScript.
One option would be to use comprehensions:
for item <- items do
IO.inspect(item)
end
Another option is to enumerate:
Enum.each items, fn(item) ->
IO.inspect(item)
end
Another option would be to useEnum.map/2
. Enum.each/2
always returns :ok
, while map/2
iterates over the list and returns new values (equivalent to Javascript's Array.map
)
iex(3)> Enum.map([1, 2, 3], fn x -> x * x end)
[1, 4, 9]
If you want to use foreach
specifically, you could use Erlang's foreach/2
:
:lists.foreach(fn a -> IO.puts a + a end, [1,2,3])
# 2
# 4
# 6
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.