方案:旋转功能不起作用

时间:2013-04-07 22:57:32

标签: rotation scheme

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

我想制作如果列表(abcde),print((abcde)(bcdea)(cdeab)(deabc)(eabcd))的功能,但是当我执行该功能时,它会打印(eabcd)(deabc).. .....

我认为此功能会像

一样激活

尾巴|头| RES

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

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

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

1 个答案:

答案 0 :(得分: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)))))