CrazySynthax
CrazySynthax

Reputation: 15058

Are All Variables in Clojure constant?

Is there a option to assign a value to a symbol in Clojure and then reassign the same symbol? What I see now is that all variables in Clojure are constant. Is it right?

Upvotes: 3

Views: 370

Answers (3)

Stuart Goldkind
Stuart Goldkind

Reputation: 1

this seems to follow the docs at: http://funcool.github.io/clojurescript-unraveled/#state-management

    cljs.user=> (def x (volatile! 2))
    #'cljs.user/x
    cljs.user=> x
    #object [cljs.core.Volatile {:val 2}]
    cljs.user=> (deref x)
    2
    cljs.user=> (vreset! x 5)
    5
    cljs.user=> x
    #object [cljs.core.Volatile {:val 5}]
    cljs.user=> (deref x)
    5

But, I find all the stuff about "immutibles" conceptually incoherent. Maybe someone more knowledgable can comment.

Upvotes: 0

Thumbnail
Thumbnail

Reputation: 13483

  • Local names can be rebound:
  • (Global) symbols can be rebound.
  • There are several flavours of thing that (usually) a symbol can be bound to whose content is mutable:

These last each have different characteristics and purposes.

From the above:

Note - you cannot assign to function params or local bindings. Only Java fields, Vars, Refs and Agents are mutable in Clojure.

Example of rebinding local name:

(let [coll (range)
      coll (rest coll)
      coll (filter odd? coll)
      coll (take 5 coll)]
  coll)
;(1 3 5 7 9)

Upvotes: 6

Michał Marczyk
Michał Marczyk

Reputation: 84379

All local variables – whether let-bound or fn-bound (fn parameters) – are constant, that's right. (They are like mathematical variables in that you can evaluate the expressions they're involved in under various assignments of values to variables, but during any single such evaluation the assigned value must be held constant.)

Note that such locals can be shadowed by identically named locals in nested scopes; the shadowing locals can have independent values, but they also cannot be reassigned.

There is also a distinct concept of Vars – the top-level objects most commonly introduced by def forms. These can have their root values rebound, and additionally, if marked :dynamic, can be rebound thread-locally.

Upvotes: 2

Related Questions