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
&String.capitalize/1turns a named function into a value by name and arity.&String.first/1maps the guest list to initials, joined with dots.&(String.upcase(&1) <> "!")is a whole function body with&1as its argument.
Keywords and builtins used here
EnumIOString
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.
Step 2 of 3 in Enum & pipes, step 14 of 27 in Language basics.