Replacement! change and remind

I had a problem understanding how these functions update the base ref, atom, etc.

The docs say: (apply f arguments to the current identity value)

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

So I wonder how it is β€œexpanded” in the application form. He did not mention what β€œarguments” are in the form used. Is this 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 

It:

 (apply + 1 1 2 3 '()) ;or (apply + 1 [1 2 3]) (def two (atom [])) (swap! two conj 10 20) ;; #=> [10 20] 

It:

 (apply conj [] [10 20]) ;or (apply conj [] 10 20 '()) 
+4
source share
1 answer

Walkthrough that you indicated from swap! docstring, means that what happens is the equivalent of replacing the new Atom value from the old one with (apply f old-value args) , where args is the seq of all the additional arguments passed before swap! .

What is actually happening is different, but it is just an implementation detail. For the sake of curiosity: Atoms have a Java method called swap , which is overloaded to take one to four arguments. The first one is always IFn ( f passed to swap! ); the second and third, at present, are the first two additional arguments for this IFn ; the fourth, if present, is ISeq additional arguments beyond the first two. apply never involved, and fixed cases of arity do not even call the IFn applyTo method (they just use invoke ). This improves performance in the general case when not too many extra arguments are passed to swap! .

+6
source

Source: https://habr.com/ru/post/1313033/


All Articles