Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why it is possible to redefine Var (given that in FP values are immutable)?

Tags:

clojure

I am using Counterclockwise to run a REPL, but I noticed this on Leiningen too.

I can call def to define a var twice. For example,

=> (def a 1)
#'fractal.core/a
=> a
1
=> (def a 2)
#'fractal.core/a
=> a
2

Clojure is a Functional Programming language and in FP objects are supposed to be immutable. If I can do this in what sense a is immutable?

Thanks for any comments.

like image 897
Soldalma Avatar asked Apr 22 '13 12:04

Soldalma


2 Answers

The entire point of vars is that they can be rebound, hence the name: var -> variable.

From the docs:

Clojure is a practical language that recognizes the occasional need to maintain a persistent reference to a changing value. ... Vars provide a mechanism to refer to a mutable storage location that can be dynamically rebound (to a new storage location) on a per-thread basis.

You are not changing any immutable value by rebinding a var.

Think of it of just giving an immutable value a name, and later give another immutable value that name.

like image 131
sloth Avatar answered Sep 20 '22 15:09

sloth


re -defing a var (that is, setting the root binding, as opposed to temporary/thread-local re-binding) is mostly intended to be a tool for development. Since standard global functions and values (those defined with def/defn) are var-based, you can redefine them without having to restart the clojure program you're editing.

Note that vars are not values, they're explicitly intended to be mutable references to values/functions.

like image 32
Joost Diepenmaat Avatar answered Sep 21 '22 15:09

Joost Diepenmaat