これが私の質問の例です。
Example:
atom = a
list2 = (a (b c a (a d)))
output = (a a (b c a a (a a d)))
どうすればスキームでこれを行うことができますか、ありがとう
これが私の質問の例です。
Example:
atom = a
list2 = (a (b c a (a d)))
output = (a a (b c a a (a a d)))
どうすればスキームでこれを行うことができますか、ありがとう
この問題の解決に使用される一般的な構造を明確に理解すれば、この問題の解決策をプログラムするのは難しくありません。これは宿題のように見えるので、自分で解決策を見つけさせます。空欄に記入するだけです。
(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)))
次のレシピをお勧めします。
各ステップを個別に解決する方法を考える必要があります。
(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))))]))