【问题标题】:Elisp: how can I express else-ifElisp:我如何表达 else-if
【发布时间】:2016-11-19 15:06:22
【问题描述】:

在 elisp 中,if 语句逻辑只允许我使用 if 情况和 else 情况。

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

但是如果我想做一个 else-if 怎么办?我需要在 else 案例中添加一个新的 if 语句吗?只是看起来有点乱。

【问题讨论】:

标签: lisp elisp


【解决方案1】:

嵌套如果

由于(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”是明智的首选方法。
  • @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 的代码,要遵循的代码稍微有点混乱。如果我不使用if 之外的任何额外功能,我从不使用cond。例如。 (if test then else)我从不写cond
  • 是的,我没有说“从不使用它”的原因之一。有时嵌套的if(或多个when,包裹在or中,内部有if)比cond更清晰。
猜你喜欢
  • 1970-01-01
  • 2019-09-04
  • 2012-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多