How to append to a nested list in a Clojure atom?

匆匆过客 提交于 2019-12-21 17:44:13

问题


I want to append a value to a list in a Clojure atom:

(def thing (atom {:queue '()}))

I know when it's not an atom, I can do this:

(concat '(1 2) '(3))

How can I translate that into a swap! command?

Note: I asked a similar question involving maps: Using swap to MERGE (append to) a nested map in a Clojure atom?


回答1:


user=> (def thing (atom {:queue '()}))
#'user/thing
user=> (swap! thing update-in [:queue] concat (list 1))
{:queue (1)}
user=> (swap! thing update-in [:queue] concat (list 2))
{:queue (1 2)}
user=> (swap! thing update-in [:queue] concat (list 3))
{:queue (1 2 3)}



回答2:


If you write your own fn then it should be side effect free because it may call several time.

(def thing (atom {:queue '()})) 

(swap! thing (fn [c]
    (update-in c [:queue] concat '(1 2 3 3))))


来源:https://stackoverflow.com/questions/22293134/how-to-append-to-a-nested-list-in-a-clojure-atom

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!