Elixir 用布尔类型来表示 true 和 false 这两个值。这样的值只有两个:true 和 false。它们可以用布尔运算符(and/2、or/2和not/1)组合起来:
true_variable = true and true
false_variable = true and false
true_variable = false or true
false_variable = false or false
true_variable = not false
false_variable = not true
and/2、or/2和not/1都是严格布尔运算符,也就是说它们要求_第一个_实参必须是布尔值。此外还有一些等效的布尔运算符,它们可以接受任意类型的实参:&&/2、||/2和!/1。
布尔运算符使用_短路求值_,也就是说,只有当需要时才会对运算符右侧的表达式求值。
每个运算符的优先级都不同,not/1会先于and/2和or/2求值。可以用括号让表达式的某一部分先于其他部分求值:
not true and false
# => false
not (true and false)
# => true
在编写返回布尔值的函数时,习惯上会在函数名末尾加上?。存储布尔值的变量也可以使用同样的约定。
def either_true?(a?, b?) do
a? or b?
end