在Chicken Scheme中将列表转换为循环列表?

3

在尝试寻找如何转换这样的列表时,我遇到了Scheme流和循环列表。然而,该答案需要Racket中不可用的功能。有人能指导我如何在Chicken Scheme中完成这个任务吗?或以一种Scheme变体中立的方式?

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

2

如果使用 SRFIs,这就非常简单:

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接