[英]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它在 Clojure 中引发 class 强制转换异常,并且
Unhandled clojure.lang.ExceptionInfo
#object[TypeError TypeError: f.call is not a function]
in ClojureScript.在 ClojureScript 中。
Just use assoc
or assoc-in
:只需使用
assoc
或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
. update
和update-in
需要 function,而不是assoc
和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.在您的示例中,字符串
"bar"
将用作 function,但无法调用字符串,因此您会看到错误。
So, you can also use a function that ignores its argument and always returns the same thing.因此,您也可以使用忽略其参数并始终返回相同内容的 function。
(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.当然,这种方式首先破坏了使用
update
而不是assoc
的原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.