typestar

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

  1. Two generators nest automatically, so every suit meets every face.
  2. rem(n, 2) == 0 filters the odd numbers out before the body runs.
  3. into: %{} collects {n, n * n} tuples into a map instead of a list.

Keywords and builtins used here

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.

Type this snippet

Step 3 of 3 in Control flow, step 21 of 27 in Language basics.

← Previous Next →