3

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?

4

2 回答 2

3

如果您可以改变列表,这是一种标准方法:

(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)))

请注意,以上将修改输入列表。除此之外,它按预期工作:

(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
于 2013-10-16T21:35:50.240 回答
2

使用 SRFI 非常简单:

(使用 srfi-1) (define l '(1 2 3 4)) (应用循环列表 l)

于 2014-09-15T15:36:24.213 回答