문제

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?

도움이 되었습니까?

해결책

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

다른 팁

It is pretty simple when you use SRFIs:

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

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top