Why using "|" in a map is calling update instead of put ?

73 views
Skip to first unread message

mG S

unread,
Jan 16, 2018, 11:16:24 AM1/16/18
to elixir-lang-core
Hi everyone, 

Well the whole question fits in the subject...
I was wondering why the pipe operator used in a map was sugar for Map.update and not Map.put

iex(1)> m=%{foo: 1}
%{foo: 1}
iex(2)> %{m | bar: 2}
** (KeyError) key :bar not found in: %{foo: 1}
    (stdlib) :maps.update(:bar, 2, %{foo: 1})
    (stdlib) erl_eval.erl:255: anonymous fn/2 in :erl_eval.expr/5
    (stdlib) lists.erl:1262: :lists.foldl/3
iex(2)> %{m | foo: 2}
%{foo: 2}


I'm sure it has good reasons, but I'm a little puzzled on why ?

charlott...@gmail.com

unread,
Jan 16, 2018, 11:56:10 AM1/16/18
to elixir-lang-core
The syntax for updating maps (ie: `%{x | foo: :bar}`) assumes the key is already set on the map, this is to, not only, avoid bugs but to allow potential optimizations

In https://hexdocs.pm/elixir/Map.html you can see that this is an expected behaviour

Maps also support a specific update syntax to update the value stored under existing atom keys:

charlott...@gmail.com

unread,
Jan 16, 2018, 11:58:47 AM1/16/18
to elixir-lang-core
as a side note, you can note that erlang has :maps.put (inserts/replace a k/v) and :maps.update (only replaces an existing kv),

elixir mimics this by having Map.put for insert/replace and %{x | atom: :atom} for replace (note that Map.update/4 has a different behaviour and is too complex for this case where you simply want to set an specific value to a map that should have the expected key)

mG S

unread,
Jan 17, 2018, 5:11:01 AM1/17/18
to elixir-lang-core
Any exemple about "avoid bugs but to allow potential optimizations" ? just curious actually...

Ben Wilson

unread,
Jan 19, 2018, 11:43:05 AM1/19/18
to elixir-lang-core
Notably, this mailing list is for proposals for the development of the language. General questions are better suited for the forums, slack, irc, or other more general discussion areas.

SEGALIS Morgan

unread,
Jan 20, 2018, 10:55:09 AM1/20/18
to elixir-l...@googlegroups.com
Sorry wasn’t aware of that...

--
You received this message because you are subscribed to a topic in the Google Groups "elixir-lang-core" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/elixir-lang-core/HCHiY9ctjrg/unsubscribe.
To unsubscribe from this group and all its topics, send an email to elixir-lang-co...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/elixir-lang-core/ef39ecfc-8e92-4bfa-8272-b78e354b3528%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.
--
Morgan SEGALIS
Reply all
Reply to author
Forward
0 new messages