Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure: Inconsistent results using assoc-in

Tags:

clojure

Can someone explain what's the reasoning behind the following results using (assoc-in)?

(assoc-in {:foo {:bar {:baz "hello"}}} [:foo :bar] "world")
=> {:foo {:bar "world"}}

(assoc-in {:foo {:bar nil}} [:foo :bar :baz] "world")
=> {:foo {:bar {:baz "world"}}}

(assoc-in {:foo {:bar "hello"}} [:foo :bar :baz] "world")
=> ClassCastException java.lang.String cannot be cast to clojure.lang.Associative  clojure.lang.RT.assoc (RT.java:702)

Apparently I can replace a map and even nil with another data type (e.g. String) but I can not replace a data type (e.g. String) with a map, because it need that data type to be already a map.

And how would one work around this? I would like to achieve the following:

(assoc-in {:foo {:bar "hello"}} [:foo :bar :baz] "world")
=> {:foo {:bar {:baz "world"}}}
like image 860
Kreisquadratur Avatar asked Feb 14 '23 20:02

Kreisquadratur


2 Answers

assoc-in is implemented on top of assoc. You can replace maps and nil because assoc works on them:

(assoc {} :foo :bar)  ;=> {:foo :bar}
(assoc nil :foo :bar) ;=> {:foo :bar}

But assoc doesn't work on strings:

(assoc "string" :foo :bar) ;=> ClassCastException

As an aside, the definition of assoc-in is quite graceful:

(defn assoc-in
  ;; metadata elided
  [m [k & ks] v]
  (if ks
    (assoc m k (assoc-in (get m k) ks v))
    (assoc m k v)))

If you need to replace a value that assoc can't be called on you need to instead act on one level shallower and replace the whole map rather than just the value:

(assoc-in {:foo {:bar "hello"}} [:foo :bar] {:baz "world"})
;=> {:foo {:bar {:baz "world"}}}

If there are other values within the map that you don't want to lose by replacing the whole thing, you can use update-in with assoc:

(update-in {:foo {:bar "hello"}} [:foo] assoc :baz "hi")
;=> {:foo {:bar "hello", :baz "hi"}}
like image 155
jbm Avatar answered Feb 23 '23 08:02

jbm


Reasoning: The problem is that your :bar is pointing to string "hello" not to a map. As work around you can use tangrammer's idea

like image 26
r00tt Avatar answered Feb 23 '23 07:02

r00tt