Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make reference/pointer in clojure?

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.

like image 269
boucekv Avatar asked Mar 24 '26 12:03

boucekv


2 Answers

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
like image 152
Rörd Avatar answered Mar 26 '26 04:03

Rörd


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.

like image 32
Jared314 Avatar answered Mar 26 '26 04:03

Jared314



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!