What is the different between these code, please further more explain the differents

i am looking at the GitHub project


and I try to copy it to my current project and modify it, so i want to understand what is the different between 2 set of code?

add_entry

  def add_entry(todo_list, entry) do
    entry = Map.put(entry, :id, todo_list.auto_id)
    new_entries = Map.put(todo_list.entries, todo_list.auto_id, entry)

    %Todo.List{todo_list | entries: new_entries, auto_id: todo_list.auto_id + 1}
  end
  

and

def add_entry(%Todo.List{entries: entries, auto_id: auto_id} = todo_list,entry) do
    entry = Map.put(entry, :id, auto_id)
    new_entries = Map.put(entries, auto_id, entry)

    %Todo.List{todo_list | entries: new_entries, auto_id: auto_id + 1}
  end
  

update_entry

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

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

and

def update_entry( %Todo.List{entries: entries} = todo_list, entry_id,updater_fun) do
    case entries[entry_id] do
      nil -> todo_list

      old_entry ->
        old_entry_id = old_entry.id
        new_entry = %{id: ^old_entry_id} = updater_fun.(old_entry)
        new_entries = Map.put(entries, new_entry.id, new_entry)
        %Todo.List{todo_list | entries: new_entries}
    end

The bottom ones will error with functionclauseerror if you don’t provide the correct struct; the top ones will not error if you provide a map that looks sufficiently like the expected struct; exact differences are an exercise left to the reader

4 Likes