30
loading...
This website collects cookies to deliver better user experience
Enum
and Stream
modules provide most of the functionality that you would typically want from a loop. Stream
module will not be explored in depth in this post.numbers = [1, 2, 3, 4]
squares = Enum.map(numbers, fn x -> x * x end)
true
being returned from a given function.numbers = [1, 2, 3, 4]
odds = Enum.filter(list, fn x -> rem(x, 2) == 1 end)
true
being returned when passed into a given function.numbers = [1, 2, 3, 4]
first_even = Enum.find(list, fn x -> rem(x, 2) == 0 end)
let list = [1, 2, 3, 4, 5];
let squares = [];
for (let i = 0; i < list.length; i++) {
squares.push(list[i] * list[i]);
}
list = [1, 2, 3, 4, 5]
squares = for n <- list, do: n * n
list = [1, 2, 3, 4, 5]
squares_of_odds = for n <- list, rem(n, 2) == 1, do: n * n
list = [1, 2, 3, 4, 5]
squares = [x * x for x in list]
# you could also use the power operator and write it like this
squares = [x**2 for x in list]
# if you only wanted to square the odd numbers
squares_of_odds = [x**2 for x in [1, 2, 3, 4] if x % 2 == 1]
:into
and :reduce
options, which you can learn about here.