O'Reilly logo

Programming Elixir by Dave Thomas

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

Chapter 5Anonymous Functions

  • Anonymous functions

  • Pattern matching and arguments

  • Higher-order functions

  • Closures

  • The & function literal

Elixir is a functional language, so it is no surprise that 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 ...

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