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

リスト(abcde)の場合、((abcde)(bcdea)(cdeab)(deabc)(eabcd))を出力する関数を作成したいのですが、その関数を実行すると(eabcd)(deabc)..... ..

この機能は次のようにアクティブになると思います

しっぽ | 頭 | 解像度

'() | (アブデ) | '()

| | (bcde) | (ちなみに)

(アブ) | (cde) | (cdeab)

(abc) | (デ) | (deabc)

(abcd) | (e) | (eabcd)

(アブデ) | () | (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 に答える