如何在嵌套原子映射中添加元素- Clojure



我得到这个错误:无法调用" clojore .lang. iatom .swap(clojore .lang. swap)。IFn, Object, Object)"因为"atom"是零。

我想在一个原子映射中添加一个关键字值。我哪里出错了?(我也试过减少)



(def !my-map (atom {1 {:id   1
:name {:first "ali" :last "veli"}}
2 {:id   2
:name {:first "batu" :last "can"}}}))
;expected output:
;        {1 {:id 1
;  :name {:first "ali" :last "veli" :fullname "ali veli"}}
;         2 {:id 2
;  :name {:first "batu" :last "can" :fullname "batu can"}}}

((fn [y]
(let [{:keys [first last]} y]
(swap! (get-in @!my-map [:name]) assoc :fullname (str first " " last))
))
(for [len (range 1 (+ 1 (count @!my-map)))]
(get-in @!my-map [len :name])
)
;=> ({:first "ali", :last "veli"} {:first "batu", :last "can"})
)

(swap! !my-map update-vals
(fn [v]
(update v :name
(fn [n]
(let [{:keys [first last]} n]
(assoc n :fullname (str first " " last)))))))

试试这个:

(swap! !my-map update-vals #(assoc-in % [:name :fullname]
(str (-> % :name :first)
" "
(-> % :name :last))))

结果:

{1 {:id 1, :name {:first "ali", :last "veli", :fullname "ali veli"}},
2 {:id 2, :name {:first "batu", :last "can", :fullname "batu can"}}}

我认为最好是抽象出更新函数,否则意图很快就会变得不可见。

(defn attach-full-name [{{:keys [first last]} :name 
:as data}]
(update data :name assoc :full (str first " " last)))

(swap! !my-map update-vals attach-full-name)
;; {1 {:id 1, :name {:first "ali", :last "veli", :full "ali veli"}},
;;  2 {:id 2, :name {:first "batu", :last "can", :full "batu can"}}}
(require '[com.rpl.specter :as s])
(->> !my-map
(s/transform
[s/ATOM s/ALL s/LAST :name (s/collect-one :first) (s/collect-one :last) :fullname]
(partial apply format "%s %s")))

相关内容

  • 没有找到相关文章

最新更新