如何在Scheme中将所有出现的给定原子的列表加倍

时间:2012-12-29 17:33:24

标签: scheme

这是关于我的问题的一个例子。

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

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

我怎么能在计划中做到这一点,谢谢

3 个答案:

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

我建议以下食谱:

  1. 当您处理没有子列表的平面列表时,如何解决这个问题?
  2. 现在,使用相同的方法处理子列表。最初,您可能希望假设子列表是平的,但最终您需要处理子列表的子列表。
  3. 您需要考虑如何分别解决每个步骤。

答案 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))))]))