Search code examples
clojure

Does def in clojure save the return value of a function or will the function get evaluated each time?


Let's say I define a function

(defn func [a] a)

Then I define

(def funcUsage (func 5))

If I now use funcUsage twice, does the function func get called twice or is the return value stored into funcUsage? I.e

(println funcUsage)
(println funcUsage)

Would that be equivalent to

(println (func 5))
(println (func 5))

? It seems like that in my program. Does def store the value of an evaluated function?


Solution

  • When you evaluate (def funcUsage (func 5)), func is called once and value 5 is bound to symbol funcUsage.

    When you evaluate

    (println funcUsage)
    (println funcUsage)
    

    you only print value of symbol, func is not called again. So, these calls:

    (println funcUsage)
    (println funcUsage)
    

    (func is not called) and

    (println (func 5))
    (println (func 5))
    

    (func is called twice) are not equivalent.

    You can also test it, if you add some side effect for func like this: (defn func [a] (println "I am called...") a) or (defn func [a] (Thread/sleep 1000) a).