Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

clojure

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?

like image 608
szxk Avatar asked Dec 19 '22 17:12

szxk


2 Answers

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)}
like image 100
Alex Miller Avatar answered Jan 13 '23 22:01

Alex Miller


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))))
like image 40
Mamun Avatar answered Jan 14 '23 00:01

Mamun