2

I would like to change normal behavior of code

(def a 5)
(def b a)
(def a 1)
b
5

To this behavior

(def a 5)
(*something* b a)
(def a 1)
b
1

It is just for learning purposes so please do not try any deep sense in this.

3
  • That's not how variables in Lisp family languages work. Commented Sep 19, 2013 at 8:28
  • In Common Lisp you can do it with symbol macros. I googled and found this for you: github.com/clojure/tools.macro Commented Sep 19, 2013 at 8:30
  • 1
    Please, don't code in imperative style while you do functional programming. Commented Sep 19, 2013 at 11:21

2 Answers 2

8

As an addition to Jared314's answer, I would like to point out that if you make a itself an atom or ref, b will automatically be something like a pointer or reference to a:

(def a (atom 5))
(def b a)
@b ;=> 5
(reset! a 1)
@b ;=> 1
Sign up to request clarification or add additional context in comments.

Comments

4

When you redefine a, you are not changing the value of a like you would in another language. It might be better to think of a as a constant. You have created a new a. This is part of the design philosophy of Clojure.

If you want something like a pointer, take a look at refs and atoms.

Atom:

(def a 5)
(def b (atom a))
@b ;=> 5
(def a 1)
@b ;=> 5
(reset! b a)
@b ;=> 1

Ref:

(def a 5)
(def b (ref a))
@b ;=> 5
(def a 1)
@b ;=> 5
(dosync
 (ref-set b a))
@b ;=> 1

Note: the @ is used to dereference b. It is shorthand for the deref function, and is required to get the value of b.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.