Clojure: Variable

By Xah Lee. Date: . Last updated: .

define global variable

Use def to set a value to a variable. Variable does not need to be declared.

;; define a var
(def x 3)
x ; 3

def can be used to change a variable's value.

;; define a var
(def x 3)
(pr x) ;  3

;; reset to 4
(def x 4)
(pr x) ;  4

Local Constants: let

To create local constants, use let. It has this form

(let [var1 val1 var2 val2 …] body)

(let [x 3] x) ; 3
(def x 4)

(let [x 3]
  (pr x)
) ; 3

(pr x) ; 4

You can bind multiple variables:

(let [x 3
      y 4]
  (+ x y)) ; 7

Later variable can use values of previous variables:

(let [x 3
      y x]
  (+ x y)) ; 6

the value part can be any expression.

(let [x 3
      y (+ 2 x)]
  (+ x y)) ; 8

Binding Form

The first arg of let is called “binding form”. It is also used in function definition. [see Clojure: Functions]

Clojure's binding form is very flexible. You can do Destructure Binding. [see Clojure: Binding Forms, Destructuring]