Search code examples
listracket

Circular lists in Racket


It has been a while since i last programmed in Racket. Now i wanted to make a circular list in Racket as follows :

(define x (list 1 2))
(set-mcdr! (cdr x) x)

But this gives rises to the error :

set-mcdr!: contract violation
expected: mpair?
given: '(2)
argument position: 1st
other arguments...:
 '(1 2)

I'm surprised because (cddr x) is '() so I don't understand why he tells me "expected: mpair?" as '(2) is a pair (with cdr the empty list).

Thanks for your help!


Solution

  • The list must be mutable if you want set-mcdr! to work, and all procedures used must also operate on mutable pairs; please check the documentation and notice that all the procedures contain an m as part of their name. For example, try this:

    (require racket/mpair)
    
    (define x (mlist 1 2))
    (set-mcdr! (mcdr x) x)