Using Comprehensions
Learn to use Elixir's comprehensions.
We'll cover the following
for
Elixir has the for
special form that offers a shortcut syntax over the most basic operations of enumerables, it is also known as a comprehension. We can iterate, map, and filter easily. Take a look:
iex> for a <- ["dogs", "cats", "flowers"], do: String.upcase(a)
#Output -> ["DOGS", "CATS", "FLOWERS"]
The expression after for
is a generator expression that will assign each item of the list to the variable a
. The result of the expression in the do
option will be in the new list. We can have more than one generator:
iex> for a <- ["Willy", "Anna"], b <- ["Math", "English"], do: {a, b}
#Output -> [{"Willy", "Math"}, {"Willy", "English"}, {"Anna", "Math"}, {"Anna", "English"}]
We’ve associated each student with a discipline using two generators.
Get hands-on with 1400+ tech skills courses.