Daniel
Daniel

Reputation: 271

need help for substitute function in scheme

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

Answers (2)

Óscar López
Óscar López

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

user102008
user102008

Reputation: 31323

I think you got your var and list mixed up

Upvotes: 1

Related Questions