Is it so bad to write a simple helper function?

def update_if_exists(map, key, fun) do
  case Map.has_key?(map, key) do
    false -> map
    true -> Map.update(map, key, nil, fun)
  end
end

-Greg Vaughn

> On Oct 3, 2017, at 1:40 PM, Ary Borenszweig <[email protected]> wrote:
> 
> I saw it, but it's different from what I want. There are two versions:
> - get_and_update(map, key, fun): fun is called with the current value under 
> key in map (or nil if key is not present in map) -> I don't want that nil, it 
> will break my code
> - get_and_update!(map, key, fun): raises if there's no key
> 
> I want something like this:
> 
> ~~~
> Map.put_lazy(map, key, fun value -> value + 1 end)
> ~~~
> 
> Here, the function is only invoked if key is present in map. `get_and_update` 
> would invoke that function with `nil`.
> 
> 
> 
> On Tuesday, October 3, 2017 at 3:00:43 PM UTC-3, Tallak Tveide wrote:
> https://hexdocs.pm/elixir/Map.html#get_and_update!/3
> 
> -- 
> 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 [email protected].
> To view this discussion on the web visit 
> https://groups.google.com/d/msgid/elixir-lang-core/1164ddd8-de7d-4e0d-b140-63db6b6b6646%40googlegroups.com.
> For more options, visit https://groups.google.com/d/optout.

-- 
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 [email protected].
To view this discussion on the web visit 
https://groups.google.com/d/msgid/elixir-lang-core/ACCFF228-CB54-480A-B642-86677B8F13F7%40gmail.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to