gpt4 book ai didi

rotation - 方案:旋转功能不起作用

转载 作者:行者123 更新时间:2023-12-01 14:06:17 25 4
gpt4 key购买 nike

(define rotate
(lambda (ls)
(define subrotate
(lambda (head tail res)
(if (null? tail)
res
(subrotate (append head (list (car tail)))
(cdr tail)
(cons (append tail head) res)))))
(if (null? ls)
ls
(subrotate '() ls '())))) (rotate '(a b c d e))

我想创建函数 if list (a b c d e), print ((a b c d e) (b c d e a) (c d e a b) (d e a b c) (e a b c d)) 但是当我执行该函数时,它会打印 (e a b c d) (d e a b c) .. .....

我觉得这个功能会像激活一样

尾部 |头 |资源

'() | (a b c d e) | '()

一个 | (b c d e) | (b c d e a)

(a b) | (c d e) | (c d e b)

(a b c) | (d e) | (d e a b c)

(a b c d) | (e) | (e a b c d)

(a b c d e) | () | (a b c d e)

我希望它只打印 (a b c d e) 但结果不是。我该如何修改它以及为什么它会打印每个旋转?

最佳答案

问题在于您向输出列表添加新元素的方式。这应该修复它:

(define rotate
(lambda (ls)
(define subrotate
(lambda (head tail res)
(if (null? tail)
res
(subrotate (append head (list (car tail)))
(cdr tail)
(append res (list (append tail head))))))) ; modified
(if (null? ls)
ls
(subrotate '() ls '()))))

或者,您可以简单地反转输出列表:

(define rotate
(lambda (ls)
(define subrotate
(lambda (head tail res)
(if (null? tail)
(reverse res) ; modified
(subrotate (append head (list (car tail)))
(cdr tail)
(cons (append tail head) res)))))
(if (null? ls)
ls
(subrotate '() ls '()))))

为了好玩,下面是同一算法的更紧凑的实现,这次使用命名的 let:

(define (rotate ls)
(let subrotate ((head '()) (tail ls) (res '()))
(if (null? tail)
(reverse res)
(subrotate (append head (list (car tail)))
(cdr tail)
(cons (append tail head) res)))))

关于rotation - 方案:旋转功能不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15868847/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com