Anonymous Functions
7.1 Defining and calling
add = fn a, b -> a + b end
add.(1, 2) # 3 — note the dot for anonymous function calls
square = fn x -> x * x end
square.(5) # 257.2 Multiple clauses
All clauses must have the same arity.
handle = fn
{:ok, result} -> "Success: #{result}"
{:error, reason} -> "Error: #{reason}"
_ -> "Unknown"
end
handle.({:ok, 42})7.3 Closures
multiplier = 3
times = fn x -> x * multiplier end
times.(5) # 15 — captures multiplier7.4 The capture operator &
add = &(&1 + &2) # same as fn a, b -> a + b end
upcase = &String.upcase/1 # capture a named function
Enum.map([1, 2, 3], &(&1 * 2))
Enum.map(["a", "b"], &String.upcase/1)
tuple_maker = &{&1, &2}
list_maker = &[&1, &2]7.5 Arity
Functions are identified by name and arity: String.split/1, String.split/2, String.split/3 are different functions.
7.6 Higher-order functions
apply_twice = fn f, x -> f.(f.(x)) end
apply_twice.(&(&1 * 2), 3) # 12
make_adder = fn n -> fn x -> x + n end end
add5 = make_adder.(5)
add5.(10) # 15