Soldalma
Soldalma

Reputation: 4758

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

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.

Upvotes: 12

Views: 1081

Answers (3)

Joost Diepenmaat
Joost Diepenmaat

Reputation: 17773

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.

Upvotes: 5

Don Stewart
Don Stewart

Reputation: 137947

in FP objects are supposed to be immutable.

This is incorrect.

Pure functional programming requires variables to be immutable values. However, Clojure is not a purely functional language, and allows untracked side-effects anywhere.

The majority of functional languages are impure, in this regard, as they do not track the occurence of side-effects, such as mutation, in the language itself.

Upvotes: 2

sloth
sloth

Reputation: 101052

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.

Upvotes: 13

Related Questions