elixir - How to update a map but only when key already exists -


i have been writing lot of elixir , 1 thing keeps cropping code when want update value of map if key exists, end code this:

def incsomething(state, key)   {_, state} = get_and_update_in(state.way.down.there[key], fn     nil -> :pop     j -> {nil, j + 1}   end) state end 

sometimes there's lot of code involved , there nested get_and_update_ins gets messy.

i found myself wanting use update_in, seems function more of upsert update rather difference between update , replace into in sql.

map.update/4 allows set default, doesn't allow not set anything. map.update!/3 outright errors if key missing.

is there less awkward way in standard language? or have write own?

you can use map.replace/3 - update value of key, if key exists in map.

this function available since elixir 1.5, previous versions you'll need implement yourself. fortunately, it's rather easy.

def update_existing(map, key, value)   case map     %{^key => _} -> %{map | key => value}     %{} -> map   end end 

alternatively, if want use function-style update modify slightly:

def update_existing(map, key, fun)   case map     %{^key => old} -> %{map | key => fun.(old)}     %{} -> map   end end 

Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -