Elixir - Logical Operators


Advertisements

Elixir provides 6 logical operators: and, or, not, &&, || and !. The first three, and or not are strict Boolean operators, meaning that they expect their first argument to be a Boolean. Non Boolean argument will raise an error. While the next three, &&, || and ! are non strict, do not require us to have the first value strictly as a boolean. They work in the same way as their strict counterparts. Assume variable A holds true and variable B holds 20, then −

Operator Description Example
and Checks if both values provided are truthy, if yes then returns the value of second variable. (Logical and). A and B will give 20
or Checks if either value provided is truthy. Returns whichever value is truthy. Else returns false. (Logical or). A or B will give true
not Unary operator which inverts the value of given input. not A will give false
&& Non-strict and. Works same as and but does not expect first argument to be a Boolean. B && A will give 20
|| Non-strict or. Works same as or but does not expect first argument to be a Boolean. B || A will give true
! Non-strict not. Works same as not but does not expect the argument to be a Boolean. !A will give false

NOTE − and, or, && and || are short circuit operators. This means that if the first argument of and is false, then it will not further check for the second one. And if the first argument of or is true, then it will not check for the second one. For example,

false and raise("An error")  
#This won't raise an error as raise function wont get executed because of short
#circuiting nature of and operator.

Example

Try the following code to understand all arithmetic operators in Elixir.

a = true
b = 20

IO.puts("a and b " <> to_string(a and b))

IO.puts("a or b " <> to_string(a or b))

IO.puts("not a " <> to_string(not a))

IO.puts("b && a" <> to_string(b && a))

IO.puts("b || a " <> to_string(b || a))

IO.puts("!a " <> to_string(!a))

The above program generates the following result −

a and b 20
a or b true
not a false
b && a true
b || a 20
!a false
elixir_operators.htm
Advertisements