typestar

The capture operator in Elixir

Three spellings of the & shorthand, from named-function capture to inline fragments.

# & captures a named function as a value; &1 is the first argument.
names = ["ada", "grace", "edsger"]

IO.inspect(Enum.map(names, &String.capitalize/1), label: "guests")

# &(...) is shorthand for a small fn.
initials = Enum.map(names, &String.first/1)
IO.puts("initials: #{Enum.join(initials, ".")}")

shout = &(String.upcase(&1) <> "!")
IO.puts(shout.("last call"))

How it works

  1. &String.capitalize/1 turns a named function into a value by name and arity.
  2. &String.first/1 maps the guest list to initials, joined with dots.
  3. &(String.upcase(&1) <> "!") is a whole function body with &1 as its argument.

Keywords and builtins used here

The run, in numbers

Lines
11
Characters to type
368
Tokens
103
Three-star pace
65 tpm

At the three-star pace of 65 tokens a minute, this run takes about 95 seconds.

Type this snippet

Step 2 of 3 in Enum & pipes, step 14 of 27 in Language basics.

← Previous Next →