swap! alter and alike

Posted by mekka on Stack Overflow See other posts from Stack Overflow or by mekka
Published on 2010-06-16T22:23:25Z Indexed on 2010/06/16 22:32 UTC
Read the original article Hit count: 153

Filed under:

Hello, I am having a problem understanding how these functions update the underlying ref, atom etc.

The docs say: (apply f current-value-of-identity args)

(def one (atom 0))
(swap! one inc) ;; => 1

So I am wondering how it got "expanded" to the apply form. It's not mentioned what exactly 'args' in the apply form is. Is it a sequence of arguments or are these separate values?

Was it "expanded" to:

(apply inc 0) ; obviously this wouldnt work, so that leaves only one possibility
(apply inc 0 '())


(swap! one + 1 2 3) ;; #=> 7

Was it:

(apply + 1 1 2 3 '()) ;or
(apply + 1 [1 2 3])

(def two (atom []))
(swap! two conj 10 20) ;; #=> [10 20]

Was it:

(apply conj [] [10 20]) ;or
(apply conj [] 10 20 '())

If I swap with a custom function like this:

(def three (atom 0))
(swap! three (fn [current elem] (println (class elem))) 10) ;;#=> java.Lang.Integer

Which means that the value '10' doesnt magically get changed into a seq '(10) and leads me to the conclusion, that it gets "expanded" to:

(apply f current-value-of-identity arg1 arg2 arg3... '())

Is that a correct assumption and the docs are simply lacking a better description?

© Stack Overflow or respective owner

Related posts about clojure