We cover:

Chapter 5
Anonymous Functions

Elixir is a functional language, so it’s no surprise functions are a basic type.

An anonymous function is created using the fn keyword.

 fn
  parameter-list -> body
  parameter-list -> body ...
 end

Think of fnend as being a bit like the quotes that surround a string literal, except here we’re returning a function as a value, not a string. We can pass that function value to other functions. We can also invoke it, passing in arguments.

At its simplest, a function has a parameter list and a body, separated by ->.

For example, the following defines a function, binding it to the variable sum, and then calls it:

 iex>​ sum = ​fn​ (a, b) -> a + b ​end
 #Function<12.17052888 in :erl_eval.expr/5>
 iex>​ sum.(1, 2)
 3

The first line of code creates a function that takes two parameters (named a and b). The implementation of the function follows the -> arrow (in our case it simply adds the two parameters), and the whole thing is terminated with the keyword end. We store the function in the variable sum.

On the second line of code, we invoke the function using the syntax sum.(1,2). The dot indicates the function call, and the arguments are passed between parentheses. (You’ll have noticed we don’t use a dot for named function calls—this is a difference between named and anonymous functions.)

If your function takes no arguments, you still need the parentheses to call it:

 iex>​ greet = ​fn​ -> IO.puts ​"​​Hello"​ ​end
 #Function<12.17052888 in :erl_eval.expr/5>
 iex>​ greet.()
 Hello
 :ok

You can, however, omit the parentheses in a function definition:

 iex>​ f1 = ​fn​ a, b -> a * b ​end
 #Function<12.17052888 in :erl_eval.expr/5>
 iex>​ f1.(5,6)
 30
 iex>​ f2 = ​fn​ -> 99 ​end
 #Function<12.17052888 in :erl_eval.expr/5>
 iex>​ f2.()
 99