这是关于我的问题的一个例子。
Example:
atom = a
list2 = (a (b c a (a d)))
output = (a a (b c a a (a a d)))
我怎么能在计划中做到这一点,谢谢
答案 0 :(得分: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)))
答案 1 :(得分:0)
我建议以下食谱:
您需要考虑如何分别解决每个步骤。
答案 2 :(得分:-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))))]))