Defaults and clauses
A function of Elixir can take a value the caller may leave out, and it can be written as several clauses that match different arguments. The two features meet in the same place: the clauses are tried from the top, and the first one whose pattern and guard accept the call runs. This lesson covers defaults, clauses, guards on a clause, and the error of a call that none of them accepts.
A default argument
The two backslashes after a parameter give it a default, which is used when the caller leaves the argument out. One definition then serves both calls, so a short call and a full one do not need two clauses:
default.exs
defmodule Hi do def greet(name \\ "guest"), do: "hi #{name}" end IO.puts(Hi.greet()) IO.puts(Hi.greet("Ada"))
elixir default.exs
hi guest
hi Ada
The defaulted parameter goes after the required ones; a parameter with a default before a required one makes the call ambiguous, and the compiler refuses it. A default is a value, not code that runs on every call, so it cannot depend on another argument.
Several clauses for one name
One name can be written several times, each clause with its own pattern. A call walks the clauses from the top and runs the first whose pattern fits, so an atom and a string can lead to genuinely different results under one name:
clauses.exs
defmodule Hi do def welcome(:admin), do: :all_access def welcome(name), do: {:hello, name} end IO.inspect(Hi.welcome(:admin)) IO.inspect(Hi.welcome("Ada"))
elixir clauses.exs
:all_access
{:hello, "Ada"}
The second clause is the general one: a bare name matches any value. The first clause is the special case, and it has to come first, which is the point of the order section below. A clause may also repeat a name with a different arity, as the functions lesson showed; that is a different function.
A guard chooses the clause
when adds a guard to a clause: the clause runs only when the guard is true, and otherwise the next clause is tried. The guards of the operators lesson are the ones allowed here, so comparisons and is_* checks are enough for most cases:
guards.exs
defmodule Num do def label(n) when n < 0, do: :negative def label(0), do: :zero def label(n) when n > 0, do: :positive end IO.puts(Num.label(-2)) IO.puts(Num.label(0)) IO.puts(Num.label(7))
elixir guards.exs
negative
zero
positive
The middle clause needs no guard because 0 is a pattern of its own. The third clause could drop its guard and work for every remaining number, which is a matter of how defensive the function should be: a guard that leaves a case open turns a wrong value into a FunctionClauseError instead of a wrong answer.
Clause order decides
The clauses are tried from the top, and a broad clause placed first wins every call below it. The compiler sees the problem and warns that a later clause can never match, but the program still runs and gives the wrong answer:
order.exs
defmodule Hi do def hello(_name), do: :guest def hello(:admin), do: :boss end IO.puts(Hi.hello(:admin))
elixir order.exs
guest
warning: this clause for hello/1 cannot match because a previous clause at line 2 always matches
│
3 │ def hello(:admin), do: :boss
│ ~
│
└─ order.exs:3:7
The program prints the guest answer first, then the compiler's warning arrives on the error stream, with the line it names underlined. The fix is to put the narrow patterns first and the catch-all last, as the clauses and guards sections do. A warning that names a clause is worth reading even when the program seems to work, because the branch it protects is dead.
The mistake: no clause matches
When no clause accepts the call, the function raises FunctionClauseError and names the argument it could not match. A guard that leaves a value out is the usual cause:
fail.exs
defmodule Num do def label(n) when n > 0, do: :positive end IO.puts(Num.label(-1))
elixir fail.exs
** (FunctionClauseError) no function clause matching in Num.label/1
The following arguments were given to Num.label/1:
# 1
-1
fail.exs:2: Num.label/1
fail.exs:5: (file)
The report names the argument it was given, the number -1, and the two places of the call: the clause that had no match and the line of the script. Add the clause that handles the remaining values, or widen the guard, and the call has somewhere to go. The pattern matching lesson takes the same idea to tuples, lists and maps.
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 does
def greet(name \\ "guest")allow?Answer
A call with no argument, which uses "guest"
A default fills the argument the caller left out, so greet/0 and greet/1 both work.
-
In which order are the clauses of one function tried?
Answer
From the first clause in the file to the last
The runtime walks the clauses in source order and runs the first match.
-
What does a
whenguard do on a clause?Answer
It lets the clause run only when the guard is true
A failed guard moves the call to the next clause, like a failed pattern.
-
What does the compiler say about a catch-all clause placed before a specific one?
Answer
A warning that the later clause cannot match
The earlier clause always matches, so the later one is dead code and Elixir warns.
-
What does this program print?
defmodule Hi do def greet(name \\ "guest"), do: "hi #{name}" end IO.puts(Hi.greet())Answer
hi guest
The call leaves the argument out, so the default "guest" is used.
-
What does this program print?
defmodule Hi do def greet(name \\ "guest"), do: "hi #{name}" end IO.puts(Hi.greet("Ada"))Answer
hi Ada
The explicit argument replaces the default.
-
What does this program print?
defmodule Hi do def welcome(:admin), do: :all_access def welcome(name), do: {:hello, name} end IO.inspect(Hi.welcome(:admin))Answer
:all_access
The atom matches the first clause, so the specific result is returned.
-
What does this program print?
defmodule Hi do def welcome(:admin), do: :all_access def welcome(name), do: {:hello, name} end IO.inspect(Hi.welcome("Ada"))Answer
{:hello, "Ada"}
A binary does not match the atom :admin, so the general clause runs.
-
What does this program do?
defmodule Num do def label(n) when n > 0, do: :positive end IO.puts(Num.label(-1))Answer
A FunctionClauseError, because the guard rejects -1
The only clause needs a positive number, so no clause matches -1.
-
What does this program print?
defmodule Hi do def hello(0), do: :zero def hello(n) when n > 0, do: :positive end IO.puts(Hi.hello(0))Answer
zero
The literal 0 matches the first clause before the guard of the second is tried.
Article author: Arthur Isaev