Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure def vs defn for a function with no arguments

Tags:

clojure

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?

like image 793
yazz.com Avatar asked Dec 16 '10 13:12

yazz.com


People also ask

What is a function with no arguments called?

A nullary or niladic function.

What is def Clojure?

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.

Does Clojure have closures?

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.


2 Answers

(def t0 (System/currentTimeMillis)) (defn t1 [] (System/currentTimeMillis)) (t1) ;; => 1318408717941 t0 ;; => 1318408644243 t0 ;; => 1318408644243 (t1) ;; => 1318408719361 
like image 138
jamesqiu Avatar answered Sep 24 '22 00:09

jamesqiu


defs are evaluated only once whereas defns (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 defs but not otherwise.

like image 28
Abhinav Sarkar Avatar answered Sep 24 '22 00:09

Abhinav Sarkar