parsa2820
parsa2820

Reputation: 608

Is there any reference type in racket?

I wanted to implement a doubly linked list in racket. At the beginning I wrote a simple two node list to test referencing in racket. Here is my code:

#lang racket

(struct node (val next) #:transparent #:mutable)

(define n0 (node 0 null))
(define n1 (node 1 n0))
n0
n1
(set-node-next! n0 n1)
n0
n1

Here is the corresponding output:

(node 0 '())
(node 1 (node 0 '()))
#0=(node 0 (node 1 #0#))
#0=(node 1 (node 0 #0#))

The first and second line of the output is what I expected from the code but after that I don't have any clue about what it is doing. I guess those # are related to reference, but I couldn't find anything on the web. Can anyone explain this output for me?

Thanks.

Upvotes: 0

Views: 178

Answers (1)

Leif Andersen
Leif Andersen

Reputation: 22342

You are correct about them being references. In Racket, pretty much all types (except for integers, and other compiler optimizations I won't go into here) refer to an object stored in a sort of heap. Because of that, when you called set-node-next!, you told Racket to point the structures next field back to the original struct. Basically forming a cycle:

enter image description here

The #0= notation is a way Racket is able to print out back references. You can read about it more in the docs, but in short, when you see #0=, its saying that #0# refers to this structure, and therefore if you see it, that's where the back-reference (so to speak) is.

Upvotes: 2

Related Questions