I change quite often! atom value using an anonymous function that uses one or more external values to calculate a new value. There are two ways to do this: one with what I understand is closure and the other not, and my question is, is this a better / more efficient way to do this?
Here's a simple example - adding a variable number to an atom - displaying both approaches:
(def my-atom (atom 0))
(defn add-val-with-closure [n]
(swap! my-atom
(fn [curr-val]
;; we pull 'n' from outside the scope of the function
;; asking the compiler to do some magic to make this work
(+ curr-val n)) ))
(defn add-val-no-closure [n]
(swap! my-atom
(fn [curr-val val-to-add]
;; we bring 'n' into the scope of the function as the second function parameter
;; so no closure is needed
(+ curr-val val-to-add))
n))
This is a compiled example, and, of course, you would not have written this code to solve this particular problem, because:
(swap! my-atom + n)
does the same without requiring an extra feature.
, . . , ? , - ( ).
, . , , . , .
!
A. Webb ( , ):
"" . "" "".
, Clojure, , , , - , Clojure, , , . , , , , . IMO, Clojure "" .
- , : Clojure - ? , , "" - . , , , - . A. Webb : "Whoa! ! , , .. , , ".
10 2014
A. Webb , , A. Webb omiel - , , , , .
, Clojure, - , . , . Clojure Lisp , . , homoiconicity ( " " ) , . Clojure, Clojure , . - , . Clojure , , Scala , Clojure , . - , StackOverflow , , , , - !