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 回答