【发布时间】:2016-11-19 15:06:22
【问题描述】:
在 elisp 中,if 语句逻辑只允许我使用 if 情况和 else 情况。
(if (< 3 5)
; if case
(foo)
; else case
(bar))
但是如果我想做一个 else-if 怎么办?我需要在 else 案例中添加一个新的 if 语句吗?只是看起来有点乱。
【问题讨论】:
-
见
cond
在 elisp 中,if 语句逻辑只允许我使用 if 情况和 else 情况。
(if (< 3 5)
; if case
(foo)
; else case
(bar))
但是如果我想做一个 else-if 怎么办?我需要在 else 案例中添加一个新的 if 语句吗?只是看起来有点乱。
【问题讨论】:
cond
由于(if test-expression then-expression else-expression) 和else if 的部分将嵌套一个新的if 作为else-expression:
(if test-expression1
then-expression1
(if test-expression2
then-expression2
else-expression2))
在其他语言中,else if 通常处于同一级别。在 lisps 中,我们有 cond 。这与cond 完全相同:
(cond (test-expression1 then-expression1)
(test-expression2 then-expression2)
(t else-expression2))
请注意,表达式可能就是这样。任何经常出现的表达式都类似于(some-test-p some-variable),而其他表达式通常也是如此。它们很少只是要评估的单个符号,但可以用于非常简单的条件。
【讨论】:
cond”可能是最惯用的解决方案。有时,使用嵌套 if 时事情会更清楚,但这种情况很少,以至于“使用 cond”是明智的首选方法。
(if (red? o) (if (square? o) 'red-square 'red-round) (if (square? o) 'blue-square 'blue-round)) 的东西,那么你就可以比(cond ((and (red? o) (square? o)) 'red-square) ((red? o) 'red-round) ((square? o) 'blue-square) (t 'blue-round)) 少得多的测试。对于平均每次 3.25 次测试与 2 次以及使用 cond 的代码,要遵循的代码稍微有点混乱。如果我不使用if 之外的任何额外功能,我从不使用cond。例如。 (if test then else)我从不写cond
if(或多个when,包裹在or中,内部有if)比cond更清晰。