2011-10-25 35 views
1

需要替代函數的幫助我需要編寫可以將列表中的變量替換成列表中的變量的函數。例如(subsitute-var '((p #t) (Q #f)) '(P and Q or Q))在方案

我已經寫了一些代碼

(define substitute 
    (lambda (A B list)  
    (cond  
    ((null? list) '())  
    ((list? (car list)) 
     (cons (substitute A B (car list)) (substitute A B (cdr list)))) 
    ((eq? (car list) A) (cons B (substitute A B (cdr list))))  
    (else  
     (cons (car list) (substitute A B (cdr list))))))) 

(define substitute-var 
    (lambda (list var) 
    (cond 
    ((null? list) '()) 
    ((null? var) '()) 
    ((substitute (caar var) (car (cdr (car var))) list))  
     (substitute-var list (cdr var))))) 

,但事情是,它只是替代第一對(p #t)和左邊的列表中喜歡同樣的其餘部分。我嘗試遞歸地調用substitute-var,但它也不起作用。所以我需要幫助。請幫我謝謝

+0

並且這個替代變量函數的結果應該類似於(substructure-var'((p#t)(Q #f))'(P和Q或Q))=>(#t和#f或#f) – Daniel

+0

把'list'替換爲參數是不幸的。原因是'list'是一個內建函數。我建議把它稱爲xs或類似的。 – soegaard

回答

1

我覺得你有你的varlist混合起來

1

試試這個:

(define (substitute-var var lst) 
    (if (or (null? var) (null? lst)) 
     '() 
     (substitute (car var) (cadr var) lst))) 

(define (substitute a b lst) 
    (cond ((null? lst) '()) 
     ((eq? (car lst) (car a)) 
     (cons (cadr a) (substitute a b (cdr lst)))) 
     ((eq? (car lst) (car b)) 
     (cons (cadr b) (substitute a b (cdr lst)))) 
     (else (cons (car lst) (substitute a b (cdr lst)))))) 

現在,當你的榜樣測試:

(substitute-var '((P #t) (Q #f)) '(P and Q or Q)) 

程序返回預期的答案:

(#t and #f or #f) 
+0

感謝您的幫助 – Daniel