scheme中的替换函数需要帮助吗

scheme中的替换函数需要帮助吗,scheme,Scheme,我需要编写一个函数,可以将列表对中的变量替换到列表中。例如(替代变量“((p#t)(Q#f))”(p和Q或Q)) 我写了一些代码 (define substitute (lambda (A B list) (cond ((null? list) '()) ((list? (car list)) (cons (substitute A B (car list)) (substitute A B (cdr list)

我需要编写一个函数,可以将列表对中的变量替换到列表中。例如
(替代变量“((p#t)(Q#f))”(p和Q或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
,但它也不起作用。所以我需要帮助。请帮我谢谢你

我想你把你的
var
列表
搞混了

试试这个:

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

这个替代var函数的结果应该是这样的(替代var’((p#t)(Q#f))(p和Q或Q))=>(#t和#f或#f)。不幸的是,将替代变量称为
列表
。原因是
list
是一个内置函数。我建议称之为xs或类似名称。