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
fn total, pct -> ... endis a value, and calling it takes a dot:tip.(48.60, 20).apply_twiceaccepts a function and calls it on its own result.Enum.map([1, 2, 3], double)hands the doubling function to a higher-order one.
Keywords and builtins used here
EnumFloatIOendfn
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.
Step 1 of 3 in Enum & pipes, step 13 of 27 in Language basics.