Skip to content
Tutorials Center
My learning

Topics

Lesson 46 of 48 ยท Practice and Review

Practice Exercises with Solutions

Practice Elixir with exercises on pattern matching, recursion, Enum, structs and processes. Try each one yourself, then compare with the solution.

You learn a language by writing code, not by reading about it. This lesson collects exercises on the core ideas of Elixir: pattern matching, recursion, the Enum module, structs and processes. Each exercise states a task, gives a hint and then shows a solution. Try to solve it on paper or in iex before you open the solution.

Elixir cannot run in this site's editors, so the solutions are read-only Elixir. Two editors use JavaScript stand-ins that follow the same logic, so you can check the results of the recursion and process exercises. To run the Elixir versions yourself, see Installing Elixir and Using IEx.

How to practice

Read the task Know what goes in and what comes out.
Try first Write your own version in iex.
Compare Check the solution and its notes.
Vary Change the task and solve it again.
1 / 2

Part 1: pattern matching

Exercise 1: first and rest

Write a function describe/1 that returns "empty" for [], "one: X" for a list with one element and "many, starting with X" for longer lists.

Hint: Use three function clauses: [], [x] and [x | _]. Order matters.

Solution:

ELIXIR
defmodule Lists do
  def describe([]), do: "empty"
  def describe([x]), do: "one: #{x}"
  def describe([x | _]), do: "many, starting with #{x}"
end

Lists.describe([])          # "empty"
Lists.describe([7])         # "one: 7"
Lists.describe([7, 8, 9])   # "many, starting with 7"

The clauses are tried from top to bottom. [x] must come before [x | _], because [x | _] also matches a one-element list. See Multiple Clauses and Guards.

Exercise 2: tagged results

Given a list such as [{:ok, 1}, {:error, "bad"}, {:ok, 3}], return only the values of the :ok tuples.

Solution:

ELIXIR
def oks(results) do
  for {:ok, value} <- results, do: value
end

oks([{:ok, 1}, {:error, "bad"}, {:ok, 3}])   # [1, 3]

In a comprehension, a generator pattern that does not match simply skips the element, so no filter is needed. The Enum version is Enum.flat_map(results, fn {:ok, v} -> [v]; _ -> [] end). See Comprehensions with for.

Exercise 3: pin operator

What does each line do?

ELIXIR
x = 5
{a, ^x} = {1, 5}
{b, ^x} = {2, 6}

Solution: the second line matches and binds a to 1, because ^x means "the value must equal the current value of x" (5). The third line raises a MatchError, because the second tuple element is 6, not 5. Without ^, the pattern {b, x} would match and rebind x. See Pattern Matching: The = Operator.

Part 2: recursion

Exercise 4: sum, product and length

Write sum/1 for a list of numbers using recursion and no Enum. Then make it tail-recursive.

Solution:

ELIXIR
defmodule MyList do
  # body-recursive: waits for the result before adding
  def sum([]), do: 0
  def sum([head | tail]), do: head + sum(tail)

  # tail-recursive: carries an accumulator
  def sum_tail(list), do: do_sum(list, 0)

  defp do_sum([], acc), do: acc
  defp do_sum([head | tail], acc), do: do_sum(tail, acc + head)
end

The second version makes the recursive call the last action, so the VM reuses the stack frame. For lists on the BEAM, both are fine in practice, but the accumulator style is a habit worth building. See Recursion and Tail Calls.

Exercise 5: flatten

Write flatten/1 that turns [1, [2, [3, 4]], 5] into [1, 2, 3, 4, 5]. Do not use List.flatten/1.

Solution:

ELIXIR
def flatten([]), do: []
def flatten([head | tail]) when is_list(head), do: flatten(head) ++ flatten(tail)
def flatten([head | tail]), do: [head | flatten(tail)]

The guard is_list(head) selects the clause for nested lists. The result of the nested call is joined with ++. This is simple and clear; for huge lists you would use an accumulator to avoid the repeated copying done by ++.

Try both ideas in the editor. It is JavaScript, but the shape of the solution is identical: an empty case, a nested case and a plain case.

JS Recursion exercises (JavaScript stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Part 3: Enum

Exercise 6: word lengths

Return a map from each word of ["apple", "fig", "banana", "kiwi"] to its length.

Solution:

ELIXIR
words = ["apple", "fig", "banana", "kiwi"]

Map.new(words, fn word -> {word, String.length(word)} end)
# %{"apple" => 5, "banana" => 6, "fig" => 3, "kiwi" => 4}

Map.new/2 takes an enumerable and a function returning {key, value}. The alternative is Enum.into(words, %{}, fn w -> {w, String.length(w)} end).

Exercise 7: group and count

Group the numbers 1..10 into even and odd, and count each group.

Solution:

ELIXIR
1..10
|> Enum.group_by(fn n -> if rem(n, 2) == 0, do: :even, else: :odd end)
|> Map.new(fn {kind, numbers} -> {kind, length(numbers)} end)
# %{even: 5, odd: 5}

Enum.group_by/2 returns a map from the key to a list of the elements. A second step turns each list into a count. Or use Enum.frequencies_by/2 to do both at once: Enum.frequencies_by(1..10, &(if rem(&1, 2) == 0, do: :even, else: :odd)).

Exercise 8: running total

Turn [1, 2, 3, 4] into [1, 3, 6, 10].

Solution:

ELIXIR
Enum.scan([1, 2, 3, 4], &+/2)   # [1, 3, 6, 10]

Enum.scan/2 is like Enum.reduce/3 but keeps every intermediate result. &+/2 is the capture of the + operator as a two-argument function. See The Enum Module.

Part 4: structs

Exercise 9: a bank account struct

Define a struct Account with owner and balance (default 0). Write deposit/2 and withdraw/2; withdrawing more than the balance must return {:error, :insufficient_funds}.

Solution:

ELIXIR
defmodule Account do
  @enforce_keys [:owner]
  defstruct [:owner, balance: 0]

  def deposit(%Account{balance: balance} = account, amount) when amount > 0 do
    {:ok, %Account{account | balance: balance + amount}}
  end

  def withdraw(%Account{balance: balance}, amount) when amount > balance do
    {:error, :insufficient_funds}
  end

  def withdraw(%Account{balance: balance} = account, amount) when amount > 0 do
    {:ok, %Account{account | balance: balance - amount}}
  end
end

{:ok, acct} = Account.deposit(%Account{owner: "Mia"}, 100)
Account.withdraw(acct, 30)    # {:ok, %Account{owner: "Mia", balance: 70}}
Account.withdraw(acct, 500)   # {:error, :insufficient_funds}

@enforce_keys forces callers to give an owner. Matching %Account{} in the function head ensures only accounts are accepted. The {:ok, ...} and {:error, ...} tuples are the standard way to report success or failure. See Maps and Structs and Error Handling.

Part 5: processes

Exercise 10: a counter process

Write a process that keeps a counter. It understands :increment and {:get, caller}, where it replies {:count, n}.

Solution:

ELIXIR
defmodule Counter do
  def start, do: spawn(fn -> loop(0) end)

  defp loop(n) do
    receive do
      :increment ->
        loop(n + 1)

      {:get, caller} ->
        send(caller, {:count, n})
        loop(n)
    end
  end
end

pid = Counter.start()
send(pid, :increment)
send(pid, :increment)
send(pid, {:get, self()})

receive do
  {:count, n} -> n
end
# 2

Messages from one process to another arrive in order, so both increments are handled before the :get. See Keeping State in a Process.

Exercise 11: fan out and collect

Compute the squares of [1, 2, 3, 4] in separate processes and collect them in order.

Solution:

ELIXIR
[1, 2, 3, 4]
|> Enum.map(fn n -> Task.async(fn -> n * n end) end)
|> Enum.map(&Task.await/1)
# [1, 4, 9, 16]

All tasks start first, then the second map waits for each in turn, so the order of the results matches the order of the inputs. Running the second step inside the first map would make the work sequential. See Tasks and Parallel Work.

Here is a stand-in with promises, which behave like tasks:

JS Fan out and collect (JavaScript stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

All four tasks start before any of them ends, and the results still come back in input order.

More ideas

  • Write Enum.map/2, Enum.filter/2 and Enum.reduce/3 yourself with recursion.
  • Implement a fizzbuzz/1 with case and rem/2, and then with multiple function clauses.
  • Parse "3 + 4" into {3, :+, 4} with String.split/1 and String.to_integer/1, and evaluate it with pattern matching.
  • Revisit the projects: Project: Todo List with Pure Functions and Project: Bank Account Process.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why must describe([x]) come before describe([x | _])?

    Clauses are tried top to bottom and the first match wins; [x | _] matches any non-empty list.
  2. 2. What does for {:ok, v} <- results, do: v do with {:error, "bad"} elements?

    In a generator, elements that do not match the pattern are skipped silently.
  3. 3. Which makes sum/1 tail-recursive?

    When nothing is left to do after the recursive call, the VM can reuse the current stack frame.
  4. 4. Why start all tasks before awaiting any of them?

    Awaiting inside the same loop that starts each task would wait for each one before starting the next.

Summary

  • Pattern matching in function heads and comprehensions replaces many if statements; clause order matters.
  • Write recursive functions with an empty case and a head/tail case, and use an accumulator for tail recursion.
  • Enum has a function for most shapes of data transformation: map, group_by, scan, frequencies_by and many more.
  • Structs plus pattern matching and {:ok, _} / {:error, _} tuples model state changes cleanly.
  • Processes keep state in a loop; tasks run work concurrently when you start them all before awaiting.

Next up: Elixir Interview Questions.