In Elixir, a common practice is to use anonymous functions. Creating an anonymous function is simple:
iex(1)> my_func = fn x -> x * 2 end
#Function<6.52032458/1 in :erl_eval.expr/5>
The general syntax is:
fn args -> output end
For readability, you may put parenthesis around the arguments:
iex(2)> my_func = fn (x, y) -> x*y end
#Function<12.52032458/2 in :erl_eval.expr/5>
To invoke an anonymous function, call it by the assigned name and add .
between the name and arguments.
iex(3)>my_func.(7, 5)
35
It is possible to declare anonymous functions without arguments:
iex(4)> my_func2 = fn -> IO.puts "hello there" end
iex(5)> my_func2.()
hello there
:ok
To make anonymous functions more concise you can use the capture operator &
. For example, instead of:
iex(5)> my_func = fn (x) -> x*x*x end
You can write:
iex(6)> my_func = &(&1*&1*&1)
With multiple parameters, use the number corresponding to each argument, counting from 1
:
iex(7)> my_func = fn (x, y) -> x + y end
iex(8)> my_func = &(&1 + &2) # &1 stands for x and &2 stands for y
iex(9)> my_func.(4, 5)
9
An anonymous function can also have multiple bodies (as a result of pattern matching):
my_func = fn
param1 -> do_this
param2 -> do_that
end
When you call a function with multiple bodies Elixir attempts to match the parameters you have provided with the proper function body.