Changing Your Map Without Changing It

The rule for modifying maps is pretty simple: you can’t. In exactly the same way that lists and vectors are immutable, maps are stubbornly resistant to change. But like lists and vectors, you can create a new map that is a modified copy of an existing map. One way you can make a modified copy is to add a key to a value, which you can do with assoc:

 (assoc book :page-count 362)

Which will give you this:

 {:page-count 362
  :title ​"Oliver Twist"
  :author ​"Dickens"
  :published 1838}

Using assoc is easy. You supply the original map, along with a key and a value, and you will get back a new map, just like the old one but with the key set to the new value. You can also feed more than one key/value pair ...

Get Getting Clojure now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.