Ask coding questions

← Back to all posts
Cyclic list maker.
RiAx (0)

Hello there,
I need a cyclic list for this project, something like
(define test '(a)) (set-cdr! test test).
I tried to implement it as
(define (make-cyclic list) (define (iter cur-pos) (if (null? (cdr cur-pos)) (set-cdr! cur-pos list) (iter (cdr cur-pos))))).
But it does not work as supposed.

RiAx (0)
RiAx (0)

I do not understand what was wrong, but I split the function into two:
(define (last-pair lst) (if (null? (cdr lst)) lst (last-pair (cdr lst))))
(define (make-cyclic lst) (set-cdr! (last-pair lst) lst)) and now it works.