11.3 条件组合结构

本节介绍常与 ifcond 配合使用、用于表达复杂条件的结构。andor 本身也可单独作为多条件判断结构使用。

Function: not condition

该函数用于判断 condition 是否为假。如果 conditionnil,则返回 t;否则返回 nil。函数 notnull 完全等价。如果你是在判断空列表或 nil 值,我们推荐使用 null

Special Form: and conditions…

and 特殊形式用于判断所有 conditions(条件)是否都为真。它会按照书写顺序逐个对 conditions 进行求值。

若任意一个 conditions 的求值结果为 nil,则无论剩余 conditions 的值如何,and 的结果都必然是 nil;因此 and 会立即返回 nil,并忽略剩余的 conditions

若所有 conditions 的求值结果均为非 nil,则最后一个条件的值会成为整个 and 形式的返回值。单独的 (and)(无任何 conditions)会返回 t,这是合理的 ——因为所有条件(空集)都满足非 nil 的要求。(不妨思考一下:哪一个条件不满足呢?)

以下是一个示例:第一个条件返回整数 1(非 nil),第二个条件同样返回整数 2(非 nil),第三个条件为 nil,因此后续的条件永远不会被求值。

(and (print 1) (print 2) nil (print 3))
     ⊣ 1
     ⊣ 2
⇒ nil

下面是一个更贴近实际使用的 and 示例:

(if (and (consp foo) (eq (car foo) 'x))
    (message "foo is a list starting with x"))

注意:若 (consp foo) 返回 nil,则 (car foo) 不会被执行,从而避免产生错误。

and 表达式也可以用 ifcond 来改写,写法如下:

(and arg1 arg2 arg3)
≡
(if arg1 (if arg2 arg3))
≡
(cond (arg1 (cond (arg2 arg3))))
Special Form: or conditions…

or 是一种特殊形式,用于判断所有 conditions(条件)中至少有一个为真。它会按照书写顺序逐个对所有条件进行求值。

如果任意一个 conditions 求值结果为非 nil,那么 or 的结果必然为非 nil;因此 or 会立即返回,并忽略剩余的条件。返回的值就是刚刚求值成功的那个条件的非 nil 值。

如果所有 conditions 最终都为 nil,则 or 表达式返回 nil。单独的 (or)(不带任何条件)返回 nil,这是合理的 —— 因为所有条件(空集)都为 nil。(不妨想一想:哪一个不是呢?)

例如,下面这个表达式用于判断 xnil 还是整数 0:

(or (eq x nil) (eq x 0))

and 结构一样,or 也可以用 cond 来实现。例如:

(or arg1 arg2 arg3)
≡
(cond (arg1)
      (arg2)
      (arg3))

你几乎可以用 if 来实现 or,但并不完全等价:

(if arg1 arg1
  (if arg2 arg2
    arg3))

这种写法并非完全等价,因为它可能会对 arg1arg2 进行两次求值。相比之下,(or arg1 arg2 arg3) 绝不会对任何参数求值超过一次。

Function: xor condition1 condition2

该函数返回 condition1condition2 的异或(互斥或) 布尔结果。具体来说:如果两个参数同为 nil,或同为非 nil,则 xor 返回 nil;否则,返回那个值为非 nil 的参数本身。

注意:与 or 不同,该函数总会对两个参数都进行求值(无短路特性)。


emacs

Emacs

org-mode

Orgmode

Donations

打赏

Copyright

© 2025 Jasper Hsu

Creative Commons

Creative Commons

Attribute

Attribute

Noncommercial

Noncommercial

Share Alike

Share Alike