查找并替换方案

时间:2013-09-22 23:38:01

标签: list recursion scheme

我需要编写一个程序程序来查找和替换给定的模式,并且我已经让它只在一层嵌套上工作但是当列表中的下一辆车本身就是一个列表时,我的程序没有&# 39;正确递归。

这是我到目前为止所做的:

(define replace 
    (lambda (source target replacement) 
        (if (eqv? source target)
            replacement
            (if (null? source)
                '() ;;base case

                (if (equal? target (car source))
                    (cons replacement (replace (cdr source) target replacement))

                    (cons (car source)
                    (replace (cdr source) target replacement))
                )
            )
        )
    )
)

3 个答案:

答案 0 :(得分:1)

使用时应将eqv?替换为equal?。使用eqv?并未提供您期望的结果,如下所示:

> (eqv? (list 1 2 3) (list 1 2 3))
#f
> (eqv? '(1 2) '(1 2))
#f ; some Schemes may return #t

关于您的代码,它更可读,更紧凑地写成一系列cond子句:

(define (replace source target replacement) 
  (cond ((eqv? source target) replacement)
        ((null? source)      '()) ;;base case
        ((equal? target (car source))
         (cons replacement (replace (cdr source) target replacement)))
        ((not (list? (car source)))
         (cons (car source) (replace (cdr source) target replacement)))
        (else
         (cons (replace (car source) target replacement) 
               (replace (cdr source) target replacement)))))

此外,另一种可能更清楚地说明算法的方法('句柄car并将其用于处理cdr')是:

(define (replace source target replacement)
  (cond ((null? source)'())
        ((equal? source target) replacement)
        (else (let ((next (car source))
                    (rest (cdr source)))
                (cons (if (not (list? next))
                          next
                          (replace next target replacement))
                      (replace rest target replacement)))))

答案 1 :(得分:0)

在我的初始版本中,我没有检查是否(汽车来源)是一个列表,因此它被视为一个单独的令牌,以避免我再添加一个条件:

(define replace 
    (lambda (source target replacement) 
        (if (eqv? source target)
            replacement
            (if (null? source)
                '() ;;base case

                (if (equal? target (car source))
                    (cons replacement (replace (cdr source) target replacement))

                    (if (not (list? (car source)))
                        (cons (car source) (replace (cdr source) target replacement))
                        (cons (replace (car source) target replacement) (replace (cdr source) target replacement))))))))

答案 2 :(得分:0)

您的错误是,当car不匹配且它不是原子时,您不会替换(define (replace source target replacement) (cond ((equal? source target) replacement) ;; equal, return replacement ((not (pair? source)) source) ;; not equal && not pair, return source (else (cons (replace (car source) target replacement) ;; recurse (replace (cdr source) target replacement))))) 。通过允许跟随所有对,可以写出非常紧凑的内容。

{{1}}