I have implemented like this defmodule KeyFoundError do defexception [:key, :term] def message(%__MODULE__{key: key, term: term}) do "key #{inspect(key)} found in: #{inspect(term)}" end end
defmodule MyMap do def put_new!(map, key, value) do if Map.has_key?(map, key) do raise KeyFoundError, key: key, term: map else Map.put(map, key, value) end end end and use it to ensure that an algorithm building a map with a non-predefined set of keys fulfills the requirement to write each key only once, which if it is not the case may be a signal that something is wrong with the algorithm. I agree that this is perhaps only a need in more complex, and thus, less common algorithms, like in my use case, where the keys come from an external data source, and I want to be sure that this is not sending the same key duplicated. Mário segunda-feira, 29 de Julho de 2019 às 11:27:07 UTC+1, José Valim escreveu: > > > 1. put_new and put_new! pair behaves differently from !-paired > functions, I’m not sure if it’s good thing to break expectations in that > case. > > I believe the concern here is that while all functions raise when the key > does not exist, the proposed put_new! raises when the key exists. It is how > put_new! should behave... but it is a different behaviour than the one that > already exists, highlighted by the fact a new exception would have to be > added. > > Ben commented on the second point already. > > Also, your proposal does not include any code examples or snippets on how > this pattern would be used. I personally can't recall a need for put_new!, > especially because *the best use of "static maps" is by defining all keys > upfront and then updating/replacing them*. > > *José Valim* > www.plataformatec.com.br > Skype: jv.ptec > Founder and Director of R&D > > -- You received this message because you are subscribed to the Google Groups "elixir-lang-core" group. To unsubscribe from this group and stop receiving emails from it, send an email to elixir-lang-core+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/elixir-lang-core/9ee0a828-ae90-4d38-a266-0f93aa338d99%40googlegroups.com.