Search code examples
clojure

Failed to update a map with assoc in Clojure


I have following map in my Clojure code:

typeList {"int"  {"type"    ["integer"]
                         "minimum" -2147483648
                         "maximum" 2147483647}
                 "bigint" {"type"    ["integer"]
                           "minimum" -9223372036854775808
                           "maximum" 9223372036854775807}}

I am trying to add some new values to that map and I am using assoc key for that; however it seems it is not adding the new value since the println is not giving the new keyword.

For example, let's add "asd" to the map:

(assoc typeList "asd" {"type"    ["integer"]})

However, when I try to print the new list, it returns as following:

(println typeList)

{int {type [integer], minimum -2147483648, maximum 2147483647}, bigint {type [integer], minimum -9223372036854775808, maximum 9223372036854775807}}

Am I missing something? Couldn't figure that out since I am newbie in Clojure.


Solution

  • assoc will not change the existing value typeList, instead it returns a new value with the key "asd". In other words, typeList will be unchanged and the return value from assoc will contain the "asd" key.

    Try this instead:

    (def updatedTypeList (assoc typeList "asd" {"type"    ["integer"]}))
    
    (get typeList "asd")
    ;; => nil
    
    (get updatedTypeList "asd")
    ;; => {"type" ["integer"]}