Fork me on GitHub
#beginners
<
2017-08-06
>
leira05:08:43

I'm reading Joy of Clojure 2nd edition, I'm confused by one of the sample code:

leira05:08:46

boot.user=> (def add-and-get
       #_=>   (let [ai (java.util.concurrent.atomic.AtomicInteger.)]
       #_=>     (fn [y] (.addAndGet ai y))))
#'boot.user/add-and-get
boot.user=> (add-and-get 2)
2
boot.user=> (add-and-get 2)
4
boot.user=> (add-and-get 7)
11
boot.user=>

leira05:08:31

I don't understand, shouldn't there be multiple ai instance every time add-and-get is called?

mobileink21:08:32

your def creates one ai and returns a fn that uses it. the def is only evaluated once, so you get one ai. add-and-get is a fn var - when you call it you call the one fn that was created when your def was evaluated.

leira05:08:50

OK, I get it now, add-and-get is not a function, it's a variable~

akiroz06:08:31

@leira add-and-get IS a function, the def can be equivalently written as:

(let [ai (java.util.concurrent.atomic.AtomicInteger.)]
  (def add-and-get
    (fn [y] (.addAndGet ai y))))
since let returns its last form.

noisesmith06:08:27

all else being equal, do def on the outside though

sb11:08:20

how to calculate root in Clojure? (like square?) ((enough a link))

sb11:08:52

(radical sign)

sb19:08:31

thanks!

mobileink21:08:32

your def creates one ai and returns a fn that uses it. the def is only evaluated once, so you get one ai. add-and-get is a fn var - when you call it you call the one fn that was created when your def was evaluated.

mobileink21:08:36

iow the value of add-and-get is not just a function, it's a closure. https://en.m.wikipedia.org/wiki/Closure_(computer_programming)