for comprehensions in Elixir
Two comprehensions: a hand of cards from two generators, a map from a filter and into:.
# for walks generators, filters as it goes, and collects the results.
court =
for suit <- ["hearts", "spades"], face <- ["J", "Q", "K"] do
"#{face} of #{suit}"
end
IO.inspect(court, label: "court cards")
# A filter clause drops values; into: picks the collection to build.
squares =
for n <- 1..10, rem(n, 2) == 0, into: %{} do
{n, n * n}
end
IO.inspect(squares, label: "even squares")
How it works
- Two generators nest automatically, so every suit meets every face.
rem(n, 2) == 0filters the odd numbers out before the body runs.into: %{}collects{n, n * n}tuples into a map instead of a list.
Keywords and builtins used here
IOdoendfor
The run, in numbers
- Lines
- 15
- Characters to type
- 388
- Tokens
- 99
- Three-star pace
- 70 tpm
At the three-star pace of 70 tokens a minute, this run takes about 85 seconds.
Step 3 of 3 in Control flow, step 21 of 27 in Language basics.