1

これが私の質問の例です。

Example:
atom = a
list2 = (a (b c a (a d)))

output = (a a (b c a a (a a d)))

どうすればスキームでこれを行うことができますか、ありがとう

4

3 に答える 3

1

この問題の解決に使用される一般的な構造を明確に理解すれば、この問題の解決策をプログラムするのは難しくありません。これは宿題のように見えるので、自分で解決策を見つけさせます。空欄に記入するだけです。

(define (double-atoms lst atm)
  (cond ((null? lst)                            ; if the list is empty
         <???>)                                 ; then return the empty list
        ((not (pair? (car lst)))                ; else if the current element is an atom
         (if (equal? (car lst) atm)             ; if the current element == atm
             (<???> (double-atoms <???> atm))   ; then cons two copies of the current element
             (<???> (double-atoms <???> atm)))) ; else cons one copy of the current element
        (else                                   ; else the current element is a list
         (cons (double-atoms <???> atm)         ; then advance the recursion over the car
               (double-atoms <???> atm)))))     ; also advance the recursion over the cdr

期待どおりに機能します。

(double-atoms '(a (b c a (a d))) 'a)
=> '(a a (b c a a (a a d)))
于 2012-12-29T19:23:31.290 に答える
0

次のレシピをお勧めします。

  1. サブリストのないフラットリストを扱っている場合、これをどのように解決しますか?
  2. 次に、同じアプローチを使用してサブリストを処理します。最初は、サブリストはフラットであると想定したいかもしれませんが、最終的にはサブリストのサブリストを処理する必要があります。

各ステップを個別に解決する方法を考える必要があります。

于 2012-12-29T17:45:30.363 に答える
-1
(define (double-atoms l)
  (cond
    ; nothing to double in an empty list
    [(empty? l) '()]
    ; the first element is a list 
    ; => double atoms in it 
    [(pair? (first l))
     (cons (double-atoms (first l))
           (double-atoms (rest l)))]
    ; the first element is an atom, double it
    [else (cons (first l)
                (cons (first l)
                      (double-atoms (rest l))))]))
于 2012-12-30T13:59:58.410 に答える