Elisp:如何表达else-if

16

在elisp中,if语句逻辑只允许我有一个if情况和一个else情况。

(if (< 3 5) 
  ; if case
    (foo)
  ; else case
    (bar))

但如果我想要使用else-if怎么办?我需要在else语句中再次放置一个if语句吗?这似乎有点混乱。


3
请查看cond - jkiiski
1个回答

35

嵌套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))

使用cond

在其他语言中,else if通常在同一级别上。在lisp中,我们使用cond来实现。下面是使用cond的相同示例:

(cond (test-expression1 then-expression1)
      (test-expression2 then-expression2)
      (t else-expression2))

请注意,表达式可以只是表达式。这些表达式通常像(some-test-p some-variable),其他表达式也是如此。很少情况下它们只是单个符号需要进行评估,但对于非常简单的条件语句可能会出现这种情况。

1
我认为“使用cond”可能是最惯用的解决方案。有时,嵌套的if语句会更清晰,但这种情况很少见,因此“使用cond”是一个明智的第一步。 - Vatine
@Vatine 我同意,只要if树在一个分支上很重。如果你有像这样的东西 (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 - Sylwester
没错,我没有说“永远不要使用它”的原因之一就是这个。有时候,嵌套的if(或多个when,用or包装,并带有内部的if)比cond更清晰。 - Vatine

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接