typestar

Anonymous functions in Elixir

fn builds function values: a tip calculator, a twice-applier, and one passed to Enum.map.

# fn builds a function value; calling one takes a dot before the parens.
tip = fn total, pct -> Float.round(total * pct / 100, 2) end
IO.puts("tip on 48.60: #{tip.(48.60, 20)}")

# Functions travel like any other value.
apply_twice = fn f, x -> f.(f.(x)) end
IO.puts("folded twice: #{apply_twice.(fn s -> s <> s end, "ha")}")

double = fn n -> n * 2 end
IO.inspect(Enum.map([1, 2, 3], double), label: "doubled")

How it works

  1. fn total, pct -> ... end is a value, and calling it takes a dot: tip.(48.60, 20).
  2. apply_twice accepts a function and calls it on its own result.
  3. Enum.map([1, 2, 3], double) hands the doubling function to a higher-order one.

Keywords and builtins used here

The run, in numbers

Lines
10
Characters to type
411
Tokens
115
Three-star pace
70 tpm

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

Type this snippet

Step 1 of 3 in Enum & pipes, step 13 of 27 in Language basics.

← Previous Next →

Anonymous functions in other languages