(define substitute (lambda (exp1 var exp2)
(cond ((atom exp2) (cond ((eq exp2 var) exp1) (true exp2)))
(true (cons (substitute exp1 var (car exp2))
(substitute exp1 var (cdr exp2)))))))
(define substitute-and-eval (lambda (x y z) (eval (substitute x y z))))
我知道eq exp2 var
正在检查exp2
的内存地址,并将驻留在那里的位模式与驻留在var
的内存空间中的位模式进行比较。
但是,在语句((eq exp2 var) exp1)
中,(eq exp2 var)
和exp1
之间的关系是什么呢
发布于 2020-06-26 18:33:44
(define substitute
(lambda (exp1 var exp2)
(if (atom exp2)
(if (eq exp2 var) exp1 exp2)
(cons (substitute exp1 var (car exp2))
(substitute exp1 var (cdr exp2))))))
substitute
将exp2
中出现的var
替换为exp1
。
但是,要考虑到这没有进行正确的替换(因此求值将返回错误的值),因为它没有考虑name conflicst --它应该生成fresh variables。
发布于 2020-06-25 18:27:24
一种更清晰的(IMO)格式(即使它不被认为是“标准”)可以是
(define substitute
(lambda (exp1 var exp2)
(cond
((atom exp2)
(cond
((eq exp2 var) exp1)
(true exp2)))
(true
(cons (substitute exp1 var (car exp2))
(substitute exp1 var (cdr exp2)))))))
(define substitute-and-eval
(lambda (x y z)
(eval (substitute x y z))))
在方案中,(cond (test1 body11 ...) ...)
是有条件的。
我们将逐一考虑(testN bodyN1 ...)
子句。如果testN
的计算结果为非False值,则会逐个计算表达式bodyN1 ...
,最后一个表达式的值将作为整个cond
的值返回。
如您所见,这里有两个嵌套的cond
,如果(atom exp2)
返回#t
,则考虑使用(eq exp2 var)
。如果它的值是#t
,exp1
的值将作为整个表达式(和函数)的值返回,因为每个cond
都在尾部位置。
https://stackoverflow.com/questions/62556999
复制相似问题