Using `|` when creating an instance of a new structure

The following code is copied from Elixir in Action, published by Manning.

defmodule TodoList do

  defstruct auto_id: 1, entries: HashDict.new

  def new, do: %TodoList{}

  def add(
    %TodoList{entries: entries, auto_id: auto_id} = todo_list,
    entry) do
      entry = Map.put(entry, :id, auto_id)
      new_entries = HashDict.put(entries, auto_id, entry)
      %TodoList{ todo_list |
        entries: new_entries,
        auto_id: auto_id + 1
      }
    end

end

I do not understand the use todo_list |at the end of a function addwhen creating a new one TodoList. I tried to completely remove it and could not see the difference in the result. Can someone explain to me what he is achieving?

+4
source share
1 answer

This is an abbreviated syntax for updating a map:

iex> map = %{foo: "bar"}
%{foo: "bar"}

iex> map = %{map | foo: "quux"}
%{foo: "quux"}

Please note that unlike Map.put/3you can only update existing keys, which gives you some security. It looks more like Erlang :maps.update/3.

iex> map = %{map | baz: "quux"}
** (ArgumentError) argument error
    (stdlib) :maps.update(:baz, "quux", %{foo: "bar"})
    (stdlib) erl_eval.erl:255: anonymous fn/2 in :erl_eval.expr/5
    (stdlib) lists.erl:1261: :lists.foldl/3

, , %TodoList{}, , , structs.

, , , todo_list | . , , add , , . .

+8

All Articles