Euphoria - 短路评估

当使用 andor 运算符通过 if、elsif、untilwhile 测试条件时 ,使用短路评估。 例如 −

if a < 0 and b > 0 then
   -- block of code
end if

如果 a < 0 为 false,则 Euphoria 不会费心去测试 b 是否大于 0。它知道无论如何总体结果都是 false。 同样 −

if a < 0 or b > 0 then
   -- block of code
end if

如果 a < 0 为 true,则 Euphoria 立即判定结果为 true,而不测试 b 的值,因为此测试的结果无关紧要。

一般来说,每当您出现以下形式的情况时 −

A and B

其中 A 和 B 可以是任意两个表达式,当 A 为 false 时,Euphoria 会采取捷径,并立即使整体结果为 false,甚至不看表达式 B。

同样,每当您遇到以下形式的情况时 −

A or  B

当 A 为 true 时,Euphoria 会跳过表达式 B 的求值,并声明结果为 true。

and 和 or 的短路计算仅针对 if、elsif、until 和 while 条件进行。 它不用于其他上下文。 例如 −

x = 1 or {1,2,3,4,5} -- x should be set to {1,1,1,1,1}

如果这里使用短路,您会将 x 设置为 1,甚至不查看 {1,2,3,4,5},这是错误的。

因此,短路可以用在 if、elsif、until 或 while 条件中,因为您只需要关心结果是 true 或 false,并且需要条件来产生一个原子作为结果。