O'Reilly logo

Learning Elixir by Kenny Ballou

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required