Reputation: 271
I need to write the function that can substitute the variables in the pairs of list into the list. for example (subsitute-var '((p #t) (Q #f)) '(P and Q or Q))
I have wrote some code
(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)))))
but the things is that it only substitute the first pair (p #t)
and left the rest of the list like the same. I try to call substitute-var
recursively, but it is also not working. so I need help. please help me thank you
Upvotes: 1
Views: 1221
Reputation: 236124
Try this:
(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))))))
Now, when tested with your example:
(substitute-var '((P #t) (Q #f)) '(P and Q or Q))
The procedure returns the expected answer:
(#t and #f or #f)
Upvotes: 1