Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Increment Values in a Map

I am wrapping my head around state in Clojure. I come from languages where state can be mutated. For example, in Python, I can create a dictionary, put some string => integer pairs inside, and then walk over the dictionary and increment the values.

How would I do this in idiomatic Clojure?

like image 249
David Williams Avatar asked Apr 13 '13 21:04

David Williams


1 Answers

To slightly improve @Michiel Brokent's answer. This will work if the key already doesn't present.

(update my-map :a #(if (nil? %) 1 (inc %)))
like image 146
Kannan Ramamoorthy Avatar answered Sep 20 '22 12:09

Kannan Ramamoorthy