这取决于。您确实应该尝试通过方案中的实际问题进一步缩小问题范围,因为答案将取决于您要做什么。
在惯用的方案中,大多数应该没有副作用,所以你有
(if predicate-expression
consequent-expression
alternative-expression) ;; alternative is optional but should be used anyway.
但是对于您的代码,您在分支中拥有不止一件事,例如:
int test (condition)
{
if (condition)
{
function1();
return function2();
}
else
{
function3();
return function4();
}
}
这里,为了让function1 和function3 做任何有用的事情,它必须变异、读取或写入某些东西,也称为副作用。您应该尽量避免这种情况,因此在 Scheme 中您可以使用 let 来存储临时变量,进行调用,以便在它返回时像这样使用它:
(define (test condition)
(if condition
(let ((tmp (function3)))
(function4 tmp))
(function4 (function3))))
现在。您最终将需要一些过程的副作用,然后您需要使用begin 或使用具有显式开始的cond。
(if predicate-expression
(begin
consequent-side-effect-expression
consequent-tail-expression)
(begin
alternative-side-effect-expression
alternative-tail-expression))
现在begin 将几个表达式合并为一个,begin 块的结果是它的最后一个表达式,因此您甚至可以在谓词中使用它。 Cond 在每个结果中都有一个明确的开始,所以当我需要多个结果或开始时,我经常从if 切换到cond:
(cond (predicate-expression consequent-side-effect-expression
consequent-tail-expression)
(predicate2-expression consequent2-tail-expression2)
(else alternative-side-effect-expression
alternative-tail-expression))
通常当有副作用时,您并不总是需要替代方案。例如。您实际上对 if 返回的内容不感兴趣,因为它也可能不在尾部位置。在这些情况下,(rnrs control (6)) 库中的 when 和 unless 具有显式开头:
(when expression
consequent-side-effect-expression
...
consequent-tail-expression)
(unless expression
consequent-side-effect-expression
...
consequent-tail-expression)
let 或 procedure 也有明确的开头:
(let ()
(display "hello") ; displays "hello"
5) ; returns 5
(define (test x)
(display x) ; display x
(+ x 5)) ; return x+5