typestar

Function clauses in Elixir

A launch countdown written as clauses: patterns and a guard pick the line, recursion drives the loop.

defmodule Countdown do
  # One function, several clauses; the first head that matches wins.
  def call(0), do: "liftoff!"
  def call(3), do: "ignition sequence start"
  def call(n) when rem(n, 2) == 0, do: "#{n}, holding steady"
  def call(n), do: "#{n}"

  # Recursion instead of a loop: each call peels one number off.
  def run(0), do: IO.puts(call(0))

  def run(n) do
    IO.puts(call(n))
    run(n - 1)
  end
end

Countdown.run(5)

How it works

  1. Four call clauses match top to bottom: 0 and 3 by value, even numbers by the rem guard.
  2. run(0) is the base case that prints liftoff and stops.
  3. run(n) prints its line and calls run(n - 1) — recursion standing in for a loop.

Keywords and builtins used here

The run, in numbers

Lines
17
Characters to type
410
Tokens
109
Three-star pace
75 tpm

At the three-star pace of 75 tokens a minute, this run takes about 87 seconds.

Type this snippet

Step 2 of 3 in Pattern matching, step 5 of 27 in Language basics.

← Previous Next →