Comprehensions in Elixir
| for generates | |
| Filter with guards | |
| Collect with into | |
| Bitstring generators note |
for generates
The for special form builds collections from generators, running its body once per drawn value. Read the generator arrow as drawn from, as in each n drawn from the list.
for n <- [1, 2, 3] do
n * 10
end
Each list element flows into the body and the results gather into a fresh list. One generator keeps things simple, while several generators multiply into every combination.
Filter with guards
Guards after the generator keep only the values you want, acting as a filter built into the loop. The body runs solely for values that satisfy every guard.
for n <- [1, 2, 3, 4], rem(n, 2) == 0 do
n * 100
end
Odd numbers fail the remainder test and vanish, so only 2 and 4 reach the body and return 200 and 400. Chain several comma separated guards to express tighter selection rules.
Collect with into
By default for collects into a list, but the into option redirects results into any collector. Maps, keyword lists, and even binaries accept the generated values.
for n <- [1, 2, 3], into: %{} do
{n, n * n}
end
Each pair becomes one map entry, giving squares keyed by their roots. Reach for into whenever the caller wants a map instead of a list of tuples.
Bitstring generators note
Generators also draw from binaries, matching each byte segment in turn. This turns for into a compact tool for text scans and small protocol parsers.
for <<c <- "hi">>, into: "" do
<<c + 1>>
end
Each character code grows by one and the into option rebuilds a binary, shifting hi to ij. Binary generators deserve care with multi byte text, where String tools handle graphemes more kindly.
Next: Advanced strings in Elixir
Article author: Arthur Isaev