If statement 新版本的if,它在做什么?

If statement 新版本的if,它在做什么?,if-statement,scheme,conditional,If Statement,Scheme,Conditional,我被要求用特定的输入解释函数的输出,但我不理解函数是如何工作的。它应该是if的一个新版本,但对我来说,它看起来什么都没做 (define (if-2 a b c) (cond (a b) (else c))) 在我看来,它似乎总是打印b,但我不确定。您似乎不熟悉cond表单。它的工作原理如下: (cond ((<predicate1> <args>) <actions>) ;^^-- this form evaluates to

我被要求用特定的输入解释函数的输出,但我不理解函数是如何工作的。它应该是if的一个新版本,但对我来说,它看起来什么都没做

(define (if-2 a b c)
    (cond (a b)
    (else c)))

在我看来,它似乎总是打印b,但我不确定。

您似乎不熟悉
cond
表单。它的工作原理如下:

(cond
  ((<predicate1> <args>) <actions>)
    ;^^-- this form evaluates to true or false. 
    ;  If true, we do <actions>, if not we move on to the next predicate.
  ((<predicate2> <args>) <actions>) ; We can have however many predicates we wish
  (else ;<-- else is always true.  This is our catch-all.
    <actions>))
要想弄清楚为什么它总是为您的测试返回
arg1
,回想一下,Scheme认为除了显式的假符号(通常是
#f
)和空列表
'()
之外的一切都是真的

因此,当您调用
(if-2>23)
时,cond表单的计算结果如下:

(cond
  (> 2)
  ;^---- `>` is not the empty list, so it evals to #t 
  (else 3))                              
然后,由于
cond
返回它发现的第一个与真值关联的内容,因此返回2


要使
if-2
按预期工作,您需要以不同的方式调用它,例如
(if-2(>32)'yep!'nope!)
将返回
'yep因为3大于2

为什么您认为它总是打印
b
?你理解
cond
?是的,我理解cond,例如,如果我调用(if-2<23),它计算表达式(<2),这是没有意义的。不,它计算表达式
(if-2<23)
返回
2
-就像
(if<23)
一样(你当然可以通过键入
(if-2<23)
进入REPL…。我这样做了,它返回2,但我不知道为什么。
(cond
  (> 2)
  ;^---- `>` is not the empty list, so it evals to #t 
  (else 3))