Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Re-def vars in Clojure(script)

I'm trying to find the idiomatic way to defer the initialization of a var (which I really intend to be immutable).

(def foo nil)
...
(defn init []
  ; (def foo (some-function))
  ; (set! foo (some-function)))

I know Rich Hickey said re-defing isn't idiomatic. Is set! appropriate here?

like image 775
Shaun Lebron Avatar asked Apr 18 '14 15:04

Shaun Lebron


1 Answers

I would use delay:

Takes a body of expressions and yields a Delay object that will invoke the body only the first time it is forced (with force or deref/@), and will cache the result and return it on all subsequent force calls. See also - realized?

Example usage:

(def foo (delay (init-foo))) ;; init-foo is not called until foo is deref'ed

(defn do-something []
  (let [f @foo] ;; init-foo is called the first time this line is executed,
                ;; and the result saved and re-used for each subsequent call.
    ...
    ))
like image 184
Alex Avatar answered Oct 17 '22 09:10

Alex