Skip to content
Tutorials Center
My learning

Topics

Lesson 41 of 48 ยท Projects

Project: Todo List with Pure Functions

Build a todo list in Elixir with structs, Enum, pattern matching and formatted output, then run the same logic as a JavaScript stand-in in your browser.

In this project you build a small todo list the Elixir way: no objects that change, no hidden state. Every operation is a pure function that takes the current list and returns a new one. That makes the code easy to read, easy to test and a good warm-up before the process-based projects later in the course.

You will use structs, pattern matching, the Enum module and string formatting. Elixir cannot run on this site, so the Elixir listings are read-only. Each step has a JavaScript twin in an editor, so you can run the same design and see the output. Where the output of the Elixir program is quoted, it is what the equivalent logic prints.

What we are building

Add Create a task with a title.
Complete Mark a task done by id.
Remove Delete a task by id.
Render Print the list as text.

Each step takes a list in and returns a new list out.

1 / 2

Step 1: model the data

A task has an id, a title and a done flag. A struct gives it a fixed shape with defaults, and @enforce_keys makes sure a title is always given. The list itself is wrapped in a second struct that also remembers the next id, so ids never repeat even after deletions.

ELIXIR
defmodule Todo.Task do
  @enforce_keys [:id, :title]
  defstruct [:id, :title, done: false]
end

defmodule Todo.List do
  defstruct tasks: [], next_id: 1
end

Keeping next_id inside the data is the functional answer to a counter variable: the "state" is just a value that you pass along.

Step 2: add, complete and remove

Each function takes a %Todo.List{} as its first argument and returns a new one. Pattern matching in the function head pulls the fields out, and the update syntax %{list | ...} builds the new struct.

ELIXIR
defmodule Todo do
  alias Todo.{List, Task}

  def new, do: %List{}

  def add(%List{tasks: tasks, next_id: id} = list, title) when is_binary(title) do
    task = %Task{id: id, title: String.trim(title)}
    %{list | tasks: tasks ++ [task], next_id: id + 1}
  end

  def complete(%List{tasks: tasks} = list, id) do
    case Enum.find(tasks, &(&1.id == id)) do
      nil -> {:error, :not_found}
      _task -> {:ok, %{list | tasks: Enum.map(tasks, &mark_done(&1, id))}}
    end
  end

  def remove(%List{tasks: tasks} = list, id) do
    {:ok, %{list | tasks: Enum.reject(tasks, &(&1.id == id))}}
  end

  defp mark_done(%Task{id: id} = task, id), do: %{task | done: true}
  defp mark_done(task, _other_id), do: task
end

Look closely at mark_done/2. In the first clause the name id appears twice, so it only matches when the task's id equals the id you asked for; any other task falls through to the second clause and comes back unchanged. That is a neat use of pattern matching as an equality check.

Notice that complete/2 returns {:ok, list} or {:error, :not_found}, the convention from Error Handling. add/2 always succeeds, so it returns the list directly and works well in a pipe. Appending with ++ is fine for a short list; for large lists you would prepend, as Performance and Common Pitfalls explains.

Step 3: render as text

Formatting is a function from data to a string, and has no side effects. Printing happens at the edge.

ELIXIR
def render(%Todo.List{tasks: []}), do: "Nothing to do!"

def render(%Todo.List{tasks: tasks}) do
  lines = Enum.map(tasks, &render_task/1)
  done = Enum.count(tasks, & &1.done)
  Enum.join(lines, "\n") <> "\n(#{done}/#{length(tasks)} done)"
end

defp render_task(%Todo.Task{id: id, title: title, done: done}) do
  mark = if done, do: "x", else: " "
  "#{String.pad_leading(Integer.to_string(id), 2)}. [#{mark}] #{title}"
end

The first clause handles the empty list, and the second handles everything else. & &1.done is the capture operator from Functions and Modules.

Run the design in JavaScript

Here is the same program in JavaScript. It uses frozen objects and returns new ones, so it mirrors the immutable style. The Elixir tuples {:ok, value} become { ok: value } objects.

JS Todo list with pure functions (JavaScript stand-in)

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

No output.

Every function leaves its input alone: afterComplete is a new value, and list is rebound to it, just as list = Todo.complete(list, 2) would rebind a variable in Elixir (see Immutability and Rebinding). Run it once and try to break it: what happens if you add an empty title?

Step 4: a pipeline with a command parser

To make it feel like a command-line tool, parse text commands with pattern matching on the string. In Elixir, String.split/3 plus case does the job, and a small helper turns the id text into an integer or an error.

ELIXIR
def run(list, input) do
  case String.split(input, " ", parts: 2) do
    ["add", title] -> {:ok, add(list, title)}
    ["done", id] -> with_id(id, fn n -> complete(list, n) end)
    ["rm", id] -> with_id(id, fn n -> remove(list, n) end)
    ["list"] -> {:ok, list}
    _ -> {:error, :unknown_command}
  end
end

defp with_id(text, fun) do
  case Integer.parse(text) do
    {n, ""} -> fun.(n)
    _ -> {:error, :bad_id}
  end
end

A driver can then use Enum.reduce/3 over a list of commands, printing errors and carrying the list along. Here is that driver as a JavaScript model, using a command parser built on a regular expression:

JS Running a script of commands (JavaScript stand-in)

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

No output.

The reducer carries the list through the commands. A failing command keeps the previous list, so one bad line never corrupts the state.

Ideas to extend it

  • Add due dates with the Date module and sort with Enum.sort_by/3, see Ranges, Sorting and Custom Ordering.
  • Add a rename/3 and a clear_done/1 function, each with a test.
  • Save the list to disk with :erlang.term_to_binary/1 (see Files, JSON and Serialization), or as JSON.
  • Move the list into a process, which is exactly what the next project does with a bank account.
  • Write ExUnit tests: because every function is pure, a test is just input, call and assert. See Testing with ExUnit.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the todo list store next_id inside the list struct?

    State is a value you pass along. Storing the next id with the tasks keeps every function pure and prevents id reuse after deletions.
  2. 2. In defp mark_done(%Task{id: id} = task, id), what does using id twice mean?

    A variable repeated in one pattern must bind to the same value in both places, so it works as an equality test.
  3. 3. What should complete/2 return for an unknown id?

    Expected failures are returned as error tuples. Callers can pattern-match on them or use with.
  4. 4. Where should printing happen in this design?

    Pure functions return data. Keeping side effects like IO at the edge makes the core easy to test.

Summary

  • Model data with structs and keep all state inside values that you pass along.
  • Pure functions take the list first and return a new one, so they work in pipelines.
  • Pattern matching in function heads replaces many if statements, and a repeated variable acts as an equality check.
  • Return {:ok, value} or {:error, reason} for operations that can fail.
  • Enum.reduce/3 carries state through a series of commands.
  • Rendering returns strings; printing stays at the edge.

Next up: Project: Bank Account Process.