3
(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 (abcde), print ((abcde) (bcdea) (cdeab) (deabc) (eabcd)) 但是当我执行该函数时,它会打印 (eabcd) (deabc) ..... ..

我认为这个功能会像

尾巴 | 头| 资源

'() | (abcde) | '()

一个 | (bcde) | (bcdea)

(ab) | (cde) | (cdeab)

(美国广播公司) | (de) | (deabc)

(abcd) | (e) | (eabcd)

(abcde) | () | (abcde)

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

4

1 回答 1

0

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

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

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

(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)))))
于 2013-04-08T00:27:07.833 回答