代码 #1 此代码有效
(define *o
(lambda (x y z)
(if (= y 0)
z
(*o x (sub1 y) (+ z x)))))
(*o 7 3 0)
code#2 此代码不起作用
(define *o (x y z)
(cond
((0? y) z)
(else *o x (sub1 y) (+ z x))))
(print (*o 7 3 0))
(define *o
(lambda (x y z)
(cond
((0? y) z)
(else *o x (sub1 y) (+ z x)))))
(*o 7 3 0)
code#3 此代码不起作用
(define *o (x y z)
(cond
((0? y) z)
(else *o x (sub1 y) (+ z x))))
(print (*o 7 3 0))
#2 尝试使用
(cond
而不是 (if
#3 尝试重新表述代码,省略
(lambda
我将把你的第二个例子重写为
if
,这样你就可以看到做了什么:
(define *o (x y z)
(if (0? y) ; I'm guessing this is like (zero? y)
z ; consequent is to return z
(begin ; the alternative consiste of 4 expressions
*o ; evaluates to a procedure, then thrown away
x ; evaluates to a number, then thrown away
(sub1 y) ; evaluates to a number, then thrown away
(+ z x)))) ; tail expression evaluates to a number and returned
(*0 1 2 3) ; ==> 4, due to (+ z x)
(*0 1 0 3) ; ==> 3, due to z
其意图可能是调用
*0
,但是您需要使用括号来应用它:
(define *o (x y z)
(if (0? y) ; I'm guessing this is like (zero? y)
z ; consequent is to return z
(*o x (sub1 y) (+ z x)))) ; tail recursive call
条件:
(define *o (x y z)
(cond
((0? y) z)
(else (*o x (sub1 y) (+ z x)))))