Anonymous Functions
fn a, b -> a + b end
There is more concise form:
&(&1 + &2)
Which reminds me of the Clojure anonymous function shorthand:
#(+ % %2)
The fn ... end form is more versatile, it supports pattern matching
in arguments, and allows multiple clauses.
handle_result = fn
{:ok, value} -> "Success: #{value}"
{:error, reason} -> "Error: #{reason}"
end
To call a anonymous function directly:
sum = fn a, b -> a + b end
sum.(2, 3)
If you are curious why there is a dot. There is a lenthy explaination.
But usually you don't use anoymous functions this way. In most cases, anonymous functions are passed to other functions:
Enum.reduce([1, 2, 3, 4], 0, &(&1 + &2))