Elixir in Action Book - ch04 - Updating an entry help (todo_crud.ex)

Brand new to Elixir and picked up Elixir in Action last week. I apologise if this isn’t the place to ask beginner questions — advice on where to in that case is most appreciated.

In 4.2 we go about building a To-do list to demonstrate CRUD in Elixir.


I’m going to initialise my todo list with a single entry:

$ iex todo_crud.ex

iex(1)> todo_list = TodoList.new() |> TodoList.add_entry(%{date: ~D[2018-12-19], title: "Dentist"})
  auto_id: 2,
  entries: %{1 => %{date: ~D[2018-12-19], id: 1, title: "Dentist"}}

The code to update an entry is:

  def update_entry(todo_list, entry_id, updater_fun) do
    case Map.fetch(todo_list.entries, entry_id) do
      :error ->

      {:ok, old_entry} ->
        new_entry = updater_fun.(old_entry)
        new_entries = Map.put(todo_list.entries, new_entry.id, new_entry)
        %TodoList{todo_list | entries: new_entries}

Let’s say I want to update my appointment. It’s actually a Doctor’s appointment.

Could someone demonstrate via code snippet how one uses update_entry/3?

What is updater_fun doing here?

Many thanks

Welcome to the forum!

You use it like this:

TodoList.update_entry(todo_list, 1, fn old_entry -> Map.put(old_entry, title: "Doctor") end)

The updater_fun is the anonymous function fn old_entry -> ... end above. In the code you can see that it calls this anonymous function passing 1 argument: updater_fun.(old_entry), then it overwrites your todo list with the result of you anonymous function.