Question

In trying to find how to convert such a list, I came across Scheme streams and circular lists. However, that answer requires features in Racket not available in Chicken scheme. Can Anyone point Me in the direction of how to do this in Chicken scheme instead? Or in a scheme-variant-neutral fashion?

Was it helpful?

Solution

If you can mutate the list, here's a standard way:

(define (make-circular lst)
  ; helper for finding the last pair in a list
  (define (last-pair lst)
    (if (null? (cdr lst))
        lst
        (last-pair (cdr lst))))
        ; special case: if the list is empty
  (cond ((null? lst) '())
        (else
         ; set the last pair to point to the head of the list
         (set-cdr! (last-pair lst) lst)
         lst)))

Be aware that the above will modify the input list. Other than that, it works as expected:

(make-circular '(1 2 3 4 5))
=> #0=(1 2 3 4 5 . #0#)

(car (cdr (cdr (cdr (cdr (cdr (make-circular '(1 2 3 4 5))))))))
=> 1

OTHER TIPS

It is pretty simple when you use SRFIs:

(use srfi-1) (define l '(1 2 3 4)) (apply circular-list l)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top