scheme中列表元素的替换

scheme中列表元素的替换,scheme,substitution,Scheme,Substitution,我得到的错误是,这是一个糟糕的语法-有什么线索可以解释为什么会这样吗? 该函数应该包含一个列表,以及一个旧单词,如果列表中存在旧单词,则该单词将被新词替换 (define (substitute s old new) (if (null? s) '() (if (list? (car s) false) (cond ((eq? (car s) old) (cons new (substitute (cdr s) old new))) (else

我得到的错误是,这是一个糟糕的语法-有什么线索可以解释为什么会这样吗? 该函数应该包含一个列表,以及一个旧单词,如果列表中存在旧单词,则该单词将被新词替换

(define (substitute s old new)
(if (null? s)
  '()
(if (list? (car s) false)
    (cond ((eq? (car s) old)
          (cons new (substitute (cdr s) old new)))
          (else 
          (cons (car s) (substitute (cdr s) old new)))))
(if (list? (car s)
    (cons (substitute (car s) old new) (substitute (cdr s) old new))))))
我希望您认为这意味着“如果(汽车s)不是列表”,但这实际上是无效的,因为您将两个参数传递给
list?
,而
只需要一个参数。请查找的正确语法,尤其是
if
的语法

此外,代码中还有一些括号错误,为了便于理解,正确缩进代码是绝对必要的

这是您的代码,已更正:

(if (list? (car s) false)
但是级联
if
s和
cond
s通常最好放在单个
cond
中,例如:

(define (substitute s old new)
  (if (null? s)
      '()
      (if (list? (car s))
          ; true
          (cons (substitute (car s) old new) (substitute (cdr s) old new))
          ; false
          (cond ((eq? (car s) old)
                 (cons new (substitute (cdr s) old new)))
                (else 
                 (cons (car s) (substitute (cdr s) old new)))))))
测试:

(define (substitute s old new)
  (cond
    ((null? s) 
     '())
    ((list? (car s))
     (cons (substitute (car s) old new) (substitute (cdr s) old new)))
    ((eq? (car s) old)
     (cons new (substitute (cdr s) old new)))
    (else 
     (cons (car s) (substitute (cdr s) old new)))))
> (substitute '(a b (h e l l o) c) 'l 'x)
'(a b (h e x x o) c)
> (substitute '(a b c) 'b 'x)
'(a x c)