我在读The Little Schemer.由于我的英语不好,我对这一段感到困惑:
(cond ...)也有不考虑其所有论点的财产.然而,由于这个属性,(和......)和(或......)都不能被定义为(cond ...)方面的函数,尽管两者(和......)和(或......) )可以表示为(cond ...) - 表达式的缩写:
Run Code Online (Sandbox Code Playgroud)(and a b) = (cond (a b) (else #f) and (or a b) = (cond (a #t) (else (b))
如果我理解正确,它说(和......)和(或......)可以用(cond ...)表达式替换,但不能定义为包含(cond ...)的函数.为什么会这样?它与变量参数有什么关系吗?谢谢.
ps我做了一些搜索,但只发现(cond ...)在其中一个条件评估为#f时忽略表达式.
想象一下,您编写if的函数/过程而不是用户定义的宏/语法:
;; makes if in terms of cond
(define (my-if predicate consequent alternative)
(cond (predicate consequent)
(else alternative)))
;; example that works
(define (atom? x)
(my-if (not (pair? x))
#t
#f))
;; example that won't work
;; peano arithemtic
(define (add a b)
(my-if (zero? a)
b
(add (- a 1) (+ b 1))))
Run Code Online (Sandbox Code Playgroud)
问题my-if在于,作为一个过程,每个参数都会在过程体执行之前得到评估.因此在atom?部分中(not (pair? x)),#t并且在执行#f主体之前进行了评估my-if.
对于最后一个示例,(add (- a 1) (+ b 1))无论是什么,都会对其进行评估,即使a为零,因此该过程永远不会结束.
您可以使用语法创建自己的:
(define-syntax my-if
(syntax-rules ()
((my-if predicate consequent alternative)
(cond (predicate consequent)
(else alternative)))))
Run Code Online (Sandbox Code Playgroud)
现在,您如何阅读本文的第一部分是一个模板,其中谓词结果和替代表示未评估的表达式.它被另一个替换只是重用表达式,以便:
(my-if (check-something) (display 10) (display 20))
Run Code Online (Sandbox Code Playgroud)
将被替换为:
(cond ((check-something) (display 10))
(else (display 20)))
Run Code Online (Sandbox Code Playgroud)
随着my-if10和20 的程序版本将被打印.这是怎么and和or实施为好.