在试图找到如何转换这样的列表时,我遇到了 Scheme streams and circular lists .但是,该答案需要在 Chicken 方案中不可用的 Racket 中的功能。任何人都可以指出我如何在 Chicken 方案中执行此操作的方向吗?还是以方案变体中立的方式?
最佳答案
如果你可以改变列表,这是一个标准的方法:
(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
关于scheme - 将列表转换为 Chicken 方案中的循环列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19414157/