Slide 32
Slide 32 text
Comprehensions in Elixir
● Comprehensions in Elixir allow you to quickly build data structures from
● an enumerable or a bitstring
● iex> for n <- [1, 2, 3, 4, 5], do: n * 3 #=> [3, 6, 9, 12, 15]
● The `<-` is called a generator
● Comprehension can take many generators and filters
Example comprehension with 3 generators
for x <- [1, 2, 3], y <- [4, 5, 6], z <- [7, 8, 9], rem(n, 2) == 0, do: x * y * z
#=> [28, 32, 36, 35, 40, 45, 42, 48, 54, 56, 64, 72, 70, 80, 90, 84, 96, 108, 84,
96, 108, 105, 120, 135, 126, 144, 162]
Example comprehension with a filter
for n <- [1, 2, 3, 4, 5, 6], rem(n, 2) == 0, do: n #=> [2, 4, 6]
You can combine both generators and a filter in a comprehension