我需要编写可以将列表对中的变量替换为列表的函数。例如(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 :(得分:1)
我认为你的var
和list
混淆了
答案 1 :(得分: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)