简体   繁体   中英

How do I update a string value in a hash-map in Clojure?

Why doesn't this work?

(def app-state (atom {:title "foo"}))

(swap! app-state update-in [:title] "bar")

All the examples I could find for update-in work on numerical values as opposed to a string.

It throws a class cast exception in Clojure, and

Unhandled clojure.lang.ExceptionInfo
 #object[TypeError TypeError: f.call is not a function]

in ClojureScript.

Just use assoc or assoc-in :

(def app-state (atom {:title "foo"}))

(swap! app-state assoc     :title "bazz")   => {:title "bazz"}
(swap! app-state assoc-in [:title] "bar")   => {:title "bar"}

update and update-in require a function, rather than a value like assoc and assoc-in . In your example the string "bar" would be used as a function, but strings can not be called, hence you see the error.

So, you can also use a function that ignores its argument and always returns the same thing.

(swap! app-state update-in [:title] (fn [_] "fizz"))      => {:title "fizz"}
(swap! app-state update-in [:title] (constantly "buzz"))  => {:title "buzz"}

Of course, this kind of defeats the reason to use an update instead of assoc in the first place.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM