TExcelTAD
Home › Elixir › Elixir Exercises

Elixir Exercises

Time to practise! Each exercise has a starter program that runs as-is and prints a placeholder result, so you can see the expected format. Copy it into a main.exs file, replace the TODO parts, run it with elixir main.exs and compare with the "Expected" output. Solutions are hidden below each exercise; try for a few minutes before opening them.

# Exercise Topics
1 FizzBuzz ranges, cond, Enum.map_join
2 Word frequency strings, Enum, maps, sorting
3 Recursive list functions recursion, pattern matching
4 Config parser binaries, with, error tuples
5 Bank account structs, guards, tagged tuples
6 Run-length encoding Enum.chunk_by, comprehensions
7 A GenServer todo list GenServer, call/cast
8 Parallel word lengths Task, ordering
9 Shapes protocol protocols, structs

1. FizzBuzz

For the numbers 1 to 15, produce Fizz for multiples of 3, Buzz for multiples of 5, FizzBuzz for multiples of both, and the number otherwise, joined by spaces.

Expected: 1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz

elixir · try it yourself
defmodule FizzBuzz do
  # TODO: return "Fizz", "Buzz", "FizzBuzz" or the number as a string
  def word(n), do: Integer.to_string(n)
end

IO.puts(Enum.map_join(1..15, " ", &FizzBuzz.word/1))
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
Show solution
elixir
defmodule FizzBuzz do
  def word(n) when rem(n, 15) == 0, do: "FizzBuzz"
  def word(n) when rem(n, 3) == 0, do: "Fizz"
  def word(n) when rem(n, 5) == 0, do: "Buzz"
  def word(n), do: Integer.to_string(n)
end

IO.puts(Enum.map_join(1..15, " ", &FizzBuzz.word/1))

The rem(n, 15) clause must come first, otherwise 15 would match the "Fizz" clause.

2. Word frequency

Write top_words(text, n) that returns the n most frequent words (lowercase, ignoring punctuation) as {word, count} tuples, most frequent first; ties are sorted alphabetically.

Expected: [{"the", 3}, {"cat", 2}, {"and", 1}]

elixir · try it yourself
defmodule Words do
  def top_words(_text, _n) do
    # TODO: downcase, split into words, count, sort, take n
    []
  end
end

text = "The cat sat. The cat ran! And the dog?"
IO.inspect(Words.top_words(text, 3))
[]
Show solution
elixir
defmodule Words do
  def top_words(text, n) do
    text
    |> String.downcase()
    |> String.split(~r/[^a-z']+/, trim: true)
    |> Enum.frequencies()
    |> Enum.sort_by(fn {word, count} -> {-count, word} end)
    |> Enum.take(n)
  end
end

Sorting by the tuple {-count, word} gives "highest count first, then alphabetical" in one step.

3. Recursive list functions

Without using Enum, write my_max/1 (largest element of a non-empty list) and my_filter/2 using recursion and pattern matching.

Expected: 42 and [2, 4, 6]

elixir · try it yourself
defmodule MyList do
  # TODO: recursive version
  def my_max([head | _tail]), do: head

  # TODO: keep the elements for which fun returns true
  def my_filter(list, _fun), do: list
end

IO.inspect(MyList.my_max([7, 42, 3, 19]))
IO.inspect(MyList.my_filter([1, 2, 3, 4, 5, 6], fn x -> rem(x, 2) == 0 end))
7
[1, 2, 3, 4, 5, 6]
Show solution
elixir
defmodule MyList do
  def my_max([only]), do: only
  def my_max([head | tail]), do: max(head, my_max(tail))

  def my_filter([], _fun), do: []

  def my_filter([head | tail], fun) do
    if fun.(head), do: [head | my_filter(tail, fun)], else: my_filter(tail, fun)
  end
end

4. Config parser

Parse lines like "port=8080" into a map. Return {:ok, map} when every line is valid, or {:error, {:bad_line, line}} for the first line without =. Values that look like integers become integers. Blank lines are skipped.

Expected:

text
{:ok, %{"host" => "localhost", "port" => 8080}}
{:error, {:bad_line, "debug"}}
elixir · try it yourself
defmodule Config2 do
  def parse(_text) do
    # TODO: split lines, parse each with parse_line/1, stop at the first error
    {:ok, %{}}
  end
end

IO.inspect(Config2.parse("host=localhost\nport=8080\n"))
IO.inspect(Config2.parse("host=localhost\ndebug\nport=1"))
{:ok, %{}}
{:ok, %{}}
Show solution
elixir
defmodule Config2 do
  def parse(text) do
    text
    |> String.split("\n", trim: true)
    |> Enum.reduce_while({:ok, %{}}, fn line, {:ok, acc} ->
      case parse_line(line) do
        {:ok, {key, value}} -> {:cont, {:ok, Map.put(acc, key, value)}}
        error -> {:halt, error}
      end
    end)
  end

  defp parse_line(line) do
    with [key, raw] <- String.split(line, "=", parts: 2) do
      {:ok, {String.trim(key), convert(String.trim(raw))}}
    else
      _ -> {:error, {:bad_line, line}}
    end
  end

  defp convert(raw) do
    case Integer.parse(raw) do
      {int, ""} -> int
      _ -> raw
    end
  end
end

Enum.reduce_while/3 stops early by returning {:halt, value}.

5. Bank account

Define a %Account{owner, balance} struct and deposit/2 and withdraw/2 that return {:ok, account} or {:error, reason}: amounts must be positive (:invalid_amount) and a withdrawal may not exceed the balance (:insufficient_funds).

Expected:

text
{:ok, 150}
{:error, :insufficient_funds}
{:error, :invalid_amount}
elixir · try it yourself
defmodule Account do
  defstruct owner: nil, balance: 0

  # TODO: add guards and error tuples
  def deposit(account, amount), do: {:ok, %{account | balance: account.balance + amount}}
  def withdraw(account, _amount), do: {:ok, account}
end

defmodule Demo do
  def run do
    acc = %Account{owner: "Ana", balance: 100}
    {:ok, acc} = Account.deposit(acc, 50)
    IO.inspect({:ok, acc.balance})
    IO.inspect(Account.withdraw(acc, 500))
    IO.inspect(Account.deposit(acc, -5))
  end
end

Demo.run()
{:ok, 150}
{:ok, %Account{owner: "Ana", balance: 150}}
{:ok, %Account{owner: "Ana", balance: 145}}
Show solution
elixir
defmodule Account do
  defstruct owner: nil, balance: 0

  def deposit(_account, amount) when amount <= 0, do: {:error, :invalid_amount}
  def deposit(account, amount), do: {:ok, %{account | balance: account.balance + amount}}

  def withdraw(_account, amount) when amount <= 0, do: {:error, :invalid_amount}
  def withdraw(%Account{balance: b}, amount) when amount > b, do: {:error, :insufficient_funds}
  def withdraw(account, amount), do: {:ok, %{account | balance: account.balance - amount}}
end

6. Run-length encoding

Encode "aaabccdddd" as "3a1b2c4d", then decode it back.

Expected: "3a1b2c4d" and "aaabccdddd"

elixir · try it yourself
defmodule RLE do
  # TODO: group equal neighbouring graphemes and count them
  def encode(text), do: text

  # TODO: read "<count><char>" pairs (the count may have several digits)
  def decode(code), do: code
end

encoded = RLE.encode("aaabccdddd")
IO.inspect(encoded)
IO.inspect(RLE.decode(encoded))
"aaabccdddd"
"aaabccdddd"
Show solution
elixir
defmodule RLE do
  def encode(text) do
    text
    |> String.graphemes()
    |> Enum.chunk_by(& &1)
    |> Enum.map_join(fn [char | _] = run -> "#{length(run)}#{char}" end)
  end

  def decode(code) do
    for [_, count, char] <- Regex.scan(~r/(\d+)(\D)/, code), into: "" do
      String.duplicate(char, String.to_integer(count))
    end
  end
end

7. A GenServer todo list

Complete Todo so that add/1 (cast) stores a title and list/0 (call) returns the titles in the order they were added.

Expected: ["buy milk", "call mom", "write code"]

elixir · try it yourself
defmodule Todo do
  use GenServer

  def start_link, do: GenServer.start_link(__MODULE__, [], name: __MODULE__)
  def add(title), do: GenServer.cast(__MODULE__, {:add, title})
  def list, do: GenServer.call(__MODULE__, :list)

  @impl true
  def init(items), do: {:ok, items}

  # TODO: store the title
  @impl true
  def handle_cast({:add, _title}, items), do: {:noreply, items}

  # TODO: reply with the titles in insertion order
  @impl true
  def handle_call(:list, _from, items), do: {:reply, items, items}
end

{:ok, _} = Todo.start_link()
Enum.each(["buy milk", "call mom", "write code"], &Todo.add/1)
IO.inspect(Todo.list())
[]
Show solution
elixir
@impl true
def handle_cast({:add, title}, items), do: {:noreply, [title | items]}

@impl true
def handle_call(:list, _from, items), do: {:reply, Enum.reverse(items), items}

Prepending is cheap; reversing once when reading restores the insertion order.

8. Parallel word lengths

Use Task.async/1 and Task.await_many/1 to compute String.length/1 of each word in parallel, then print word: length lines in the original order.

Expected:

text
concurrency: 11
is: 2
fun: 3
elixir · try it yourself
words = ["concurrency", "is", "fun"]

# TODO: start one task per word and await them all
results = Enum.map(words, fn word -> {word, 0} end)

Enum.each(results, fn {word, len} -> IO.puts("#{word}: #{len}") end)
concurrency: 0
is: 0
fun: 0
Show solution
elixir
words = ["concurrency", "is", "fun"]

results =
  words
  |> Enum.map(fn word -> Task.async(fn -> {word, String.length(word)} end) end)
  |> Task.await_many()

Enum.each(results, fn {word, len} -> IO.puts("#{word}: #{len}") end)

Task.await_many/1 returns results in the order of the tasks, so the output order is fixed.

9. Shapes protocol

Define a protocol Perimeter with perimeter/1 and implement it for %Square{side} and %Triangle{a, b, c} structs.

Expected: [20, 12]

elixir · try it yourself
defmodule Square, do: defstruct([:side])
defmodule Triangle, do: defstruct([:a, :b, :c])

defprotocol Perimeter do
  @fallback_to_any true
  def perimeter(shape)
end

# TODO: defimpl Perimeter for Square and Triangle
defimpl Perimeter, for: Any do
  def perimeter(_shape), do: 0
end

defmodule Demo do
  def run do
    shapes = [%Square{side: 5}, %Triangle{a: 3, b: 4, c: 5}]
    IO.inspect(Enum.map(shapes, &Perimeter.perimeter/1))
  end
end

Demo.run()
[0, 0]
Show solution
elixir
defimpl Perimeter, for: Square do
  def perimeter(%Square{side: s}), do: 4 * s
end

defimpl Perimeter, for: Triangle do
  def perimeter(%Triangle{a: a, b: b, c: c}), do: a + b + c
end

With real implementations in place, the Any fallback is only used for other types. You can remove it together with @fallback_to_any true; then unsupported values raise Protocol.UndefinedError instead of silently returning 0, which is usually better.

Test yourself

In FizzBuzz, why must the rem(n, 15) == 0 clause come first?

  1. It is faster
  2. Clauses are tried in order, so 15 would otherwise match the Fizz clause
  3. Elixir sorts clauses by guard
  4. It doesn't matter

How does Enum.reduce_while/3 stop early?

  1. By raising
  2. When the function returns {:halt, acc}
  3. When the accumulator is nil
  4. It can't

Why does the GenServer todo list prepend titles and reverse when listing?

  1. Prepending to a list is O(1), appending copies the list
  2. GenServer state must be reversed
  3. To sort the titles
  4. Lists can only grow at the front