2014-11-09 88 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)