Elixir basics · Lesson 13 (open contents)
Let function clauses choose
Define named functions with defaults, patterns, and guards.
Run this first
Run it once, change one input, and compare the new result.
# 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}.
Read from the first line down
- Read
def price(age, discount \\ 0): Declare a default second argument. - Read
when age < 12: Choose this clause only when its guard passes. - Read
_discount: Accept an argument that this clause does not use.
Symbols are not secret signs
def price(age, discount \\ 0)Declare a default second argument.
when age < 12Choose this clause only when its guard passes.
_discountAccept an argument that this clause does not use.
Match each name to its meaning
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.
Why these forms are useful
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.
Close the answer and try
Add Label.name/1 clauses for zero and positive numbers.
defmodule Label do
def name(0), do: ____
def name(number) when number > 0, do: ____
end
{Label.name(0), Label.name(3)}Target result: Return {:zero, :positive}.
Stuck? Read one hint
Return the atoms :zero and :positive.
After you run it, see one answer
defmodule Label do
def name(0), do: :zero
def name(number) when number > 0, do: :positive
end
{Label.name(0), Label.name(3)}Think about it: Which matching clause runs?
Elixir tries clauses from top to bottom and runs the first match whose guard passes.
Remember these three lines
- 1
Name and arity identify a function.
- 2
Patterns and guards select clauses.
- 3
Defaults belong in a function head when clauses follow.