Learn/Elixir/6. Functions
Lesson 6 of 8
Sign in

Elixir, lesson 6

Functions

So far your code has run from top to bottom. As programs grow, you want to give a piece of logic a name, call it from many places, and test it on its own. In Elixir, named functions always live inside a module.

Modules and def

defmodule creates the module Shop (module names start with a capital letter). def defines a public function with two parameters. There is no return keyword: a function returns the value of its last expression. You call it with the module name, a dot and the arguments.

Short functions fit on one line with do::

Several clauses

A function can have more than one clause. When you call it, Elixir tries the clauses from top to bottom and runs the first one whose parameters match. That replaces many ifs:

2 exercises to try what you just read.

Exercise 1

Prime checker

Press Ctrl Enter or Check to test your code.

Exercise 2

Volume knob

Press Ctrl Enter or Check to test your code.

Add a guard with when to require a condition on top of the pattern:

Names ending in ?, like even?, are a convention for functions that return true or false.

Private helpers and constants

defp defines a private function that only code inside the same module can call. Use it for helpers that are not part of the module's public face.

A module attribute such as @vat 20 gives a value a name for the whole module. It is the closest thing Elixir has to a constant:

Scope: what a function can see

A function only sees its own parameters and the variables it binds inside its body. Variables from the script around the module are not visible inside def. If a function needs a value, pass it in as an argument. This keeps every function self-contained: you can understand it by reading it alone.

Anonymous functions (fn ... end) are different: they can see variables bound before them. Call one with a dot: add = fn a, b -> a + b end and then add.(2, 3). The shorthand &Shop.total/2 turns a named function into a value you can pass to Enum functions.

Further reading

  • Getting started: Modules and functions
  • Getting started: Anonymous functions
  • Getting started: Module attributes

Write Prime.prime?/1, which returns true when a number is prime (it has exactly two divisors, 1 and itself) and false otherwise. Numbers below 2 are not prime.

A neat way: a private helper that tries divisors d = 2, 3, 4, ... and stops once d * d is bigger than the number.

Input: one whole number. Output: N is prime or N is not prime.

prints 97 is prime.

A speaker's volume must stay between a lowest and a highest setting. Write Knob.clamp/3, which takes a value, a low and a high and returns:

  • low if the value is below low,
  • high if the value is above high,
  • the value itself otherwise.

Use one clause per case, with guards.

Input: three lines: the requested value, then low, then high (low is never above high). Output: the clamped value.

defmodule Shop do
  def total(price, quantity) do
    price * quantity
  end
end

IO.puts(Shop.total(4, 3))   # 12
def double(n), do: n * 2
defmodule Greeter do
  def hello("Ada"), do: "Welcome back, Ada!"
  def hello(name), do: "Hello, #{name}."
end
defmodule Ticket do
  def price(age) when age < 12, do: 5
  def price(age) when age >= 65, do: 7
  def price(_age), do: 10
end
defmodule Price do
  @vat 20
  def with_vat(net), do: net + net * @vat / 100
end
97