在 cond 中省略括号会导致奇怪的结果
Omitting parentheses in cond leads to strange result
考虑以下片段
(define (f a b c)
(
cond ((and (< b c) (< b a)) (+ c a))
((and (< a c) (< a b)) (+ c b))
((and (< c b) (< c a)) (+ b a))
)
)
(display (f 2 1 3)) ; 5
(newline)
(display (f 2 8 3)) ; 11
(newline)
(display (f 2 8 -3)) ; 10
现在如果我评论第二行和倒数第二行
(define (f a b c)
;(
cond ((and (< b c) (< b a)) (+ c a))
((and (< a c) (< a b)) (+ c b))
((and (< c b) (< c a)) (+ b a))
;)
)
结果是
#<undef>
11
10
我无法解释为什么省略括号会导致该结果。在第二种情况下,我预计编译器会将 cond ((and (< b c) (< b a)) (+ c a))
、((and (< a c) (< a b)) (+ c b))
和 ((and (< a c) (< a b)) (+ c b))
视为三个表达式,后两个无效,相反它们似乎被执行了。
通常 cond
关键字在被解释时应该引发异常。
但是,如果您的解释器没有抛出任何错误,那么您是在块语句的情况下,其中最后一个表达式的计算提供了结果,其他表达式仅计算副作用。代码简化为:
(define (f a b c) ((and (< c b) (< c a)) (+ b a))))
考虑以下片段
(define (f a b c)
(
cond ((and (< b c) (< b a)) (+ c a))
((and (< a c) (< a b)) (+ c b))
((and (< c b) (< c a)) (+ b a))
)
)
(display (f 2 1 3)) ; 5
(newline)
(display (f 2 8 3)) ; 11
(newline)
(display (f 2 8 -3)) ; 10
现在如果我评论第二行和倒数第二行
(define (f a b c)
;(
cond ((and (< b c) (< b a)) (+ c a))
((and (< a c) (< a b)) (+ c b))
((and (< c b) (< c a)) (+ b a))
;)
)
结果是
#<undef>
11
10
我无法解释为什么省略括号会导致该结果。在第二种情况下,我预计编译器会将 cond ((and (< b c) (< b a)) (+ c a))
、((and (< a c) (< a b)) (+ c b))
和 ((and (< a c) (< a b)) (+ c b))
视为三个表达式,后两个无效,相反它们似乎被执行了。
通常 cond
关键字在被解释时应该引发异常。
但是,如果您的解释器没有抛出任何错误,那么您是在块语句的情况下,其中最后一个表达式的计算提供了结果,其他表达式仅计算副作用。代码简化为:
(define (f a b c) ((and (< c b) (< c a)) (+ b a))))