This page is not created by, affiliated with, or supported by Slack Technologies, Inc.
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=>
I don't understand, shouldn't there be multiple ai instance every time add-and-get is called?
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.
@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.all else being equal, do def on the outside though
@sb You can use the sqrt function in https://github.com/clojure/math.numeric-tower
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.
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)