Anonymous functions
In the previous chapter, we saw that functions are types and first-class citizens in Elixir. We even saw how to define some functions.
Anonymous functions are similar to regular functions except that they are not bound to an identifier.
Furthermore, there are actually two different syntaxes to define anonymous functions. This includes the syntax we saw earlier—fn () -> block end
. But there is also a shorter syntax variant—&(block)
. Let's dive into some examples of both of these syntaxes and general function definitions.
As we saw in the previous chapter, we had the following:
iex(1)> square = fn x -> x * x end #Function<6.90072148/1 in :erl_eval.expr/5>
Then we could use it with the following:
iex(2) square.(2) 4
So what are we doing here (at (1)
)? We are defining a function and binding it to the name square
. The function takes a single variable (call it x
), and we return the expression, x * x
, or, after evaluation, the square of x
.
The...