Scheme 试图用新元素[球拍]替换列表中元素的所有实例

Scheme 试图用新元素[球拍]替换列表中元素的所有实例,scheme,racket,Scheme,Racket,正如标题所说,我正在尝试编写一个函数,它接受一个列表、一个变量和一个元素,然后用该元素替换列表中变量的所有实例 例如: 替换“C”或“D”或“D”f将返回 'C或f或f 现在我得到的是: (define (substitute lst rep new) (cond ((or (null? lst)) lst) ((eq? (car lst) rep) (cons new (substitute (cdr lst) rep new))) (else

正如标题所说,我正在尝试编写一个函数,它接受一个列表、一个变量和一个元素,然后用该元素替换列表中变量的所有实例

例如:

替换“C”或“D”或“D”f将返回

'C或f或f

现在我得到的是:

(define (substitute lst rep new)
  (cond ((or (null? lst))
     lst)
    ((eq? (car lst) rep)
     (cons new (substitute (cdr lst) rep new)))
    (else
     (cons (car lst) (substitute (cdr lst) rep new)))))
它不会像我的示例那样检查嵌套列表,尽管当它们不是输入的一部分时,它可以正常工作


我在放置递归的位置上遇到了问题——或者说,在所有东西都以某种方式被替换后,将其展平然后重新构建会更容易吗?

下面是另一个使用模式匹配的解决方案-

它是这样工作的-

(sub '(a b c a b c a b c) 'a 'z)
;; '(z b c z b c z b c)

(sub '(a b c (a b c (a b c))) 'a 'z)
;; '(z b c (z b c (z b c)))

(sub '() 'a 'z)
; '()

乍一看,你的问题看起来很像。据我所知,您的问题略有不同,因为您还希望替换嵌套列表中的引用

为了处理嵌套列表,必须添加一个子句来检查是否存在嵌套列表,并通过递归嵌套列表替换该嵌套列表中的所有引用:

(define (subst l rep new)
  (cond ((null? l)
         '())
        ((list? (car l))  ; Check if it is a nested list.
         (cons (subst (car l) rep new)  ; Replace occurrences in the nested list.
               (subst (cdr l) rep new)))  ; Replace occurrences in the rest of the list.
        ((eq? (car l) rep)
         (cons new
               (subst (cdr l) rep new)))
        (else
          (cons (car l)
                (subst (cdr l) rep new)))))
从用户633183给出的答案中借用的示例用法:

(subst '(a b c a b c a b c) 'a 'z)
;; '(z b c z b c z b c)

(subst '(a b c (a b c (a b c))) 'a 'z)
;; '(z b c (z b c (z b c)))

(subst '() 'a 'z)
; '()

这可以使用映射和递归来完成:

(define (subst lst rep new)
    (map (lambda (x)
            (if (list? x)                    
                (subst x rep new)
                (if (eq? rep x) new x))) lst))
输出:

(subst '(a b c (a b c (a b c))) 'a 'z)
; '(z b c (z b c (z b c)))
(subst '(a b c (a b c (a b c))) 'a 'z)
; '(z b c (z b c (z b c)))