在elisp中,if语句逻辑只允许我有一个if情况和一个else情况。
(if (< 3 5)
; if case
(foo)
; else case
(bar))
但如果我想要使用else-if怎么办?我需要在else语句中再次放置一个if语句吗?这似乎有点混乱。
如果需要在(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
通常在同一级别上。在lisp中,我们使用cond
来实现。下面是使用cond
的相同示例:
(cond (test-expression1 then-expression1)
(test-expression2 then-expression2)
(t else-expression2))
(some-test-p some-variable)
,其他表达式也是如此。很少情况下它们只是单个符号需要进行评估,但对于非常简单的条件语句可能会出现这种情况。cond
”可能是最惯用的解决方案。有时,嵌套的if语句会更清晰,但这种情况很少见,因此“使用cond
”是一个明智的第一步。 - Vatine(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
代码稍微难以跟踪。如果我没有使用任何额外的功能,我从不使用cond
。例如(if test then else)
我从不写成cond
。 - Sylwesterif
(或多个when
,用or
包装,并带有内部的if
)比cond
更清晰。 - Vatine
cond
。 - jkiiski