szxk
szxk

Reputation: 1839

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

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?

Upvotes: 4

Views: 1697

Answers (2)

Mamun
Mamun

Reputation: 512

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))))

Upvotes: 3

Alex Miller
Alex Miller

Reputation: 70201

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)}

Upvotes: 8

Related Questions