2014-11-09 92 views
0
(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)))))) 

我得到的错误说这是不好的语法 - 为什么可能是什么线索? 该函数应该包含在一个列表中,以及一个旧的单词,如果它存在于列表中,则被新单词替换。替换方案中的列表元素

回答

0
(if (list? (car s) false) 

我希望你认为这意味着“如果(轿厢S)是不是列表”,而是因为你通过2个参数list?,其中只有一个预计这实际上是无效的。请查找conditionals的正确语法,尤其是if的语法。

此外,在您的代码中有几个括号错误,并且根据自己的理解正确缩进代码是绝对必要的。

这里是你的代码,修正:

(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))))))) 

但级联if S和cond s的一般最好放进一个cond如:

(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)