Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to update map value using function?

Tags:

clojure

I have a map m, a key k and a function f. Is it possible to rewrite this code simpler?

(assoc m k (f (get m k))
like image 694
DNNX Avatar asked Mar 18 '14 18:03

DNNX


People also ask

Does map set overwrite?

set() overwrites the value if the key already exists in the map. How can I test this easily when in a big project? Are there any website you can use for javascript coding? what should happen instead?

Does map function modify original array?

map() creates a new array from calling a function for every array element. map() calls a function once for each element in an array. map() does not execute the function for empty elements. map() does not change the original array.

Does map return value?

The returning value The first difference between map() and forEach() is the returning value. The forEach() method returns undefined and map() returns a new array with the transformed elements. Even if they do the same job, the returning value remains different.


2 Answers

Try clojure.core/update-in

(update-in m [k] f)

Edit: Clojure 1.7 introduced clojure.core/update

(update m k f)
like image 138
Kyle Avatar answered Sep 21 '22 12:09

Kyle


update-in does this nicely, though it's especially useful for nested maps:

> (update-in {:a 4} [:a] + 7)
{:a 11}

> (update-in {:a {:b 4 :c {:d 8}} :q :foo} [:a :c :d] + 7) 
{:a {:c {:d 15}, :b 4}, :q :foo} 
like image 36
Arthur Ulfeldt Avatar answered Sep 18 '22 12:09

Arthur Ulfeldt