I have written a program in clojure but some of the functions have no arguments. What would be the advantages of coding such functions as a "def" instead of a "defn" with no arguments?
A nullary or niladic function.
def is a special form that associates a symbol (x) in the current namespace with a value (7). This linkage is called a var . In most actual Clojure code, vars should refer to either a constant value or a function, but it's common to define and re-define them for convenience when working at the REPL.
This is a perfect opportunity to enforce encapsulation to avoid drowning the client in board-implementation details. Clojure has closures, and closures are an excellent way to group functions (Crockford 2008) with their supporting data.
(def t0 (System/currentTimeMillis)) (defn t1 [] (System/currentTimeMillis)) (t1) ;; => 1318408717941 t0 ;; => 1318408644243 t0 ;; => 1318408644243 (t1) ;; => 1318408719361
def
s are evaluated only once whereas defn
s (with or without arguments) are evaluated (executed) every time they are called. So if your functions always return the same value, you can change them to def
s but not otherwise.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With