← Back to lesson 14: Let function clauses choose

Let function clauses choose: full examples and further reading

The original lesson material is preserved here for reference. The main notebook focuses on this lesson's core question.

Define named functions with defaults, patterns, and guards.

Run two calls through different price/2 clauses and verify the results.

Run this first

Run it once, change one input, and compare the new result.

Original full example
# Define one public function with two clauses
defmodule Fare do
  def price(age, discount \\ 0)
  def price(age, _discount) when age < 12, do: 5
  def price(_age, discount), do: 10 - discount
end

{Fare.price(10), Fare.price(20, 2)}

The calls return {5, 8}.

Steps for the full example

  1. Read def price(age, discount \\ 0): Declare a default second argument.
  2. Read when age < 12: Choose this clause only when its guard passes.
  3. Read _discount: Accept an argument that this clause does not use.

Original lesson notes

Run the example first. Predict one result, then change one input and run it again.

Several definitions with the same name and arity can accept different patterns or guards.

A guard adds a permitted check after when.

Symbols and terms
def price(age, discount \\ 0)
Declare a default second argument.
when age < 12
Choose this clause only when its guard passes.
_discount
Accept an argument that this clause does not use.
function clause
Several definitions with the same name and arity can accept different patterns or guards.
guard
A guard adds a permitted check after when.
default argument
\\ supplies an argument when the caller leaves it out.

Original full exercise

Add Label.name/1 clauses for zero and positive numbers.

Exercise starter
defmodule Label do
  def name(0), do: ____
  def name(number) when number > 0, do: ____
end

{Label.name(0), Label.name(3)}

Return {:zero, :positive}.

Show hint

Return the atoms :zero and :positive.

Show original answer
Reference answer
defmodule Label do
  def name(0), do: :zero
  def name(number) when number > 0, do: :positive
end

{Label.name(0), Label.name(3)}
Which matching clause runs?

Elixir tries clauses from top to bottom and runs the first match whose guard passes.

Original lesson takeaways
Design trade-offs and language comparisons
Original course references