温馨提示:本文翻译自stackoverflow.com,查看原文请点击:clojure - Using swap! on a nested map
clojure

clojure - 使用交换!

发布于 2020-04-27 08:51:33

我正在关注《专业Clojure》一书的第6章。

应用状态目前定义如下:

(defonce app-state                                          
  (reagent/atom
    {:projects
     {"aaa"
      {:title "Build Whip"
       :stories
       {1 {:title "Design a data model for projects and stories"    
           :status "done"                                           
           :order 1}                                                
        2 {:title "Create a story title entry form"                 
           :order 2}    
        3 {:title "Implement a way to finish stories"
           :order 3}}}}}))                                            

我需要使用swap!一个新的键值来表示一个新的故事,该键值由具有给定字段值的id来键控。

(defn add-story! [app-state project-id title status]     ;
  ; Q. How to use swap! to add a key value pair into :stories?
  (swap! app-state update [:projects project-id :stories] assoc      <- INCORRECT CODE HERE
         (unique) {:title title
                   :status status
                   :order (inc (max-order app-state project-id))}))

此处未显示的唯一函数只会生成任何唯一的uuid。最大阶函数可以得到最大阶。由于书中的章节与实际提供的最终代码不一致,因此我不得不对其进行修改。这是我的max-order版本:

(defn max-order [app-state project-id]
  (apply max 0 (map :order (vals (get-in @app-state [:projects project-id :stories])))))

问题:如何使用swap!新的键值添加到:stories

我尝试了一下,但现在它击败了我。

我确实感觉到此嵌套 map不是最好的表示法-在作为下载提供的最终代码中,作者已更改为关系类型更多的模型,其中项目和故事都是顶级实体,故事包含project_id,但是swap!在继续之前先解决它的第一次使用将是一个不错的选择

查看更多

提问者
mwal
被浏览
62
Juraj Martinka 2020-02-10 13:10

我认为您可以assoc-in在这种情况下使用它,它比简单一些,update-in并且可以更好地描述您要实现的目标:

(def app-state
  (atom 
   {:projects
    {"aaa"
     {:title   "Build Whip"
      :stories {1 {:title  "Design a data model for projects and stories"
                   :status "done"
                   :order  1}
                2 {:title "Create a story title entry form"
                   :order 2}
                3 {:title "Implement a way to finish stories"
                   :order 3}}}}}))

(defn unique [] (rand-int 1000000000))

(let [unique-key (unique)]
  (swap! app-state
         assoc-in
         [:projects "aaa" :stories unique-key]
         {:title  (str "Agent " unique-key)
          :status "foxy"
          :order  "some-order-stuff"}))
@app-state
;; => {:projects
;;     {"aaa"
;;      {:title "Build Whip",
;;       :stories
;;       {1 {:title "Design a data model for projects and stories", :status "done", :order 1},
;;        2 {:title "Create a story title entry form", :order 2},
;;        3 {:title "Implement a way to finish stories", :order 3},
;;        295226401 {:title "Agent 295226401", :status "foxy", :order "some-order-stuff"}}}}}