Functions
A function in Elixir lives in a module, has a name, takes a fixed number of arguments and returns the value of its last expression. def writes the public ones, defp the private ones, and fn makes one without a name when it is passed to another function. This lesson covers the four forms and the error of a call with the wrong number of arguments.
def, a name and a body
The module is the namespace, def declares the function, and the body goes between do and end, or after do: when it is one expression. There is no return: the last expression is the result.
greet.exs
defmodule Hi do def greet(name), do: "hi #{name}" end IO.puts(Hi.greet("Ada"))
elixir greet.exs
hi Ada
The call is Module.function(arguments). Inside the module the call may drop the module name; outside it, the module is part of the name.
Arity is part of the name
The number of arguments is called the arity, and the name plus the arity identifies a function. greet/1 and greet/2 are two functions that live side by side, each with its own body, and the documentation writes the slash and the number for that reason:
arity.exs
defmodule Hi do def greet(name), do: "hi #{name}" def greet(first, last), do: "hi #{first} #{last}" end IO.puts(Hi.greet("Ada")) IO.puts(Hi.greet("Ada", "Lovelace"))
elixir arity.exs
hi Ada
hi Ada Lovelace
A call with a number that matches neither raises UndefinedFunctionError, and the message prints the name with the arity it looked for. The next section shows the same idea for a function without a name.
Anonymous functions
fn makes a function as a value: it can be bound to a name, stored in a list and passed to another function. The call needs a dot, double.(21), because the binding may hold something that is not a function and the dot makes that explicit. A named function is passed with &String.upcase/1:
anonymous.exs
double = fn x -> x * 2 end IO.puts(double.(21)) IO.inspect(Enum.map([1, 2, 3], double)) IO.inspect(Enum.map(["a", "b"], &String.upcase/1))
elixir anonymous.exs
42
[2, 4, 6]
["A", "B"]
Enum.map/2 takes a list and a function and returns the list of the results; it does not care whether the function has a name. This is the ordinary way to pass behaviour as a value, and the Enum lesson uses it throughout.
The capture shorthand
& builds the same function in a shorter form. &(&1 * 2) is fn x -> x * 2 end, with &1 standing for the first argument and &2 for the second. The same sign names an existing function, as in &String.trim/1:
capture.exs
double = &(&1 * 2) add = &(&1 + &2) IO.puts(double.(21)) IO.puts(add.(2, 3)) IO.inspect(Enum.map([" a ", " b "], &String.trim/1))
elixir capture.exs
42
5
["a", "b"]
The capture form is a convenience, not a different kind of function: the value is a function of the same arity, and it can be passed anywhere an anonymous function is accepted. A long body reads better with fn, and a one-expression callback reads better with &.
The mistake: calling with the wrong number
An anonymous function checks its arity at the call, and a mismatch stops the program with a BadArityError. The message names the arity the function has and the number it was called with:
arity_error.exs
add = fn a, b -> a + b end IO.puts(add.(1))
elixir arity_error.exs
** (BadArityError) #Function<0.106579232 in file:arity_error.exs> with arity 2 called with 1 argument (1)
arity_error.exs:2: (file)
(elixir 1.19.7) lib/code.ex:1613: Code.require_file/2
The reference between the angle brackets names the module the file compiled to, and the number in it belongs to the compiler. A reader who calls a named function with the wrong count gets UndefinedFunctionError instead, because the name and the arity form a key the module does not have. Both errors mean the same thing: the number of arguments is part of the call, not a detail of the body.
The programs on this page were run with Elixir 1.19.7 on Erlang/OTP 27 (erts 15.2.7.14), on Linux x86_64 in a Docker container.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What identifies a function in Elixir?
Answer
Its name and its arity
greet/1 and greet/2 are different functions, which is why the docs write the slash and the count.
-
How do you call an anonymous function bound to
double?Answer
double.(21)
The dot separates the value being called from its arguments.
-
What is
&(&1 * 2)?Answer
A one-argument function that multiplies its argument by 2
The capture builds the function fn x -> x * 2 end.
-
What does
defpchange about a function?Answer
Only the module that declares it may call it
defp keeps the function inside the module; a call from outside is an UndefinedFunctionError.
-
What does this program print?
add = fn a, b -> a + b end IO.puts(add.(2, 3))Answer
5
The two arguments are added and IO.puts/1 prints the result.
-
What does this program print?
IO.puts(Enum.map([1, 2, 3], &(&1 * 2)) |> Enum.sum())Answer
12
The map doubles each element and the sum adds 2, 4 and 6.
-
What does this program print?
defmodule Hi do def greet(name), do: "hi #{name}" end IO.puts(Hi.greet("Ada"))Answer
hi Ada
def is public, and the call interpolates the argument it was given.
-
What does this program print?
double = &(&1 * 2) IO.puts(double.(4))Answer
8
The capture is a function of one argument, and 4 doubled is 8.
-
What does this program do?
add = fn a, b -> a + b end IO.puts(add.(1))Answer
A BadArityError: the function has arity 2 and got one argument
An anonymous function checks the number of arguments at the call.
-
What does this program print?
IO.inspect(Enum.map([" a ", " b "], &String.trim/1))Answer
["a", "b"]
The capture names String.trim/1, and Enum.map/2 applies it to every element.
Article author: Arthur Isaev