Boolean Operators
Boolean operators help to control logical flow within your program. They perform operations on boolean values and return a boolean result (true or false). The primary boolean operators are and, or, and not.
-
and: Theandoperator returns true if both the operands are true. Otherwise, it returns false.iex> true and true true iex> true and false false -
or: Theoroperator returns true if at least one of the operands is true.iex> false or true true iex> false or false false -
not: Thenotoperator returns the opposite boolean value of the operand.iex> not true false iex> not false true
Elixir does not provide an xor infix operator. For exclusive-or on booleans, use a != b (two booleans are "xor true" exactly when they differ). If you need it spelled out, :erlang.xor/2 works too.
|
iex> true != false
true
iex> :erlang.xor(true, true)
false
Short-Circuit Operators
In addition to the boolean operators and, or, and not, Elixir provides &&, ||, and ! as equivalent short-circuit operators. Short-circuit evaluation, also known as minimal evaluation, is a method of evaluation in which the second argument is executed or evaluated only if the first argument does not suffice to determine the value of the expression.
However, these operators handle non-boolean values differently than their counterparts, which is important to understand to avoid unexpected behavior in your Elixir programs.
-
&&operator: This operator returns the first value if it is falsy (eitherfalseornil). Otherwise, it returns the second value. This is why it only evaluates the second argument if the first one is truthy.iex> nil && true nilIn the above example,
nil && truereturnsnilbecausenilis a falsy value. -
||operator: This operator returns the first value if it is truthy. Otherwise, it returns the second value. It only evaluates the second argument if the first one is falsy.iex> true || "Hello" trueIn this example,
true || "Hello"returnstruebecausetrueis a truthy value. -
!operator: This operator negates the truthiness of the value. It returnsfalsefor all truthy values andtruefor all falsy values.iex> !1 falseHere,
!1returnsfalsebecause1is considered a truthy value in Elixir.