【问题标题】:Clojure: add element to a vector inside a mapClojure:将元素添加到地图内的向量中
【发布时间】:2016-02-19 07:29:47
【问题描述】:

我有这张地图

(def m {:a "aaa" :b {:c ["ss" "gg"]}})

我想将它更新为这个(将“uu”添加到向量中:c):

{:a "aaa" :b {:c ["ss" "gg" "uu"]}}

这是我想出的,我讨厌它:

(assoc-in m [:b :c] (conj (get-in m [:b :c]) "uu"))

应该我该怎么做?

【问题讨论】:

    标签: dictionary vector clojure


    【解决方案1】:
    (update-in m [:b :c] conj "uu")
    

    我的想法是update-in 将你带到那里并调用一个函数,该函数不仅接收那里的状态,还接收剩余的参数.所以这里conj会被["ss" "gg"]"uu"调用,数据结构中的key:c的值会变成["ss" "gg" "uu"]

    assoc-in 没有获得任何初始状态,因此在您的示例中,您必须努力重新创建 there 的内容。

    【讨论】:

    • 但要注意陷阱:如果映射中没有键,conj 将创建一个列表,而不是向量:(update-in m [:b :d] conj "xxx") => {:a "aaa", :b {:c ["ss" "gg"], :d ("xxx")}}。为避免这种情况,您应该处理 nil 值,如下所示:(update-in m [:b :d] (fnil conj []) "xxx") => {:a "aaa", :b {:c ["ss" "gg"], :d ["xxx"]}}
    猜你喜欢
    • 1970-01-01
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多