Bo

Booleans in Elixir

3 exercises

About Booleans

Elixir represents true and false values with the boolean type. There are only two values: true and false. These values can be combined with boolean operators (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

The operators and/2, or/2, and not/1 are strictly boolean which means they require their first argument to be a boolean. There are also equivalent boolean operators that work any type of arguments - &&/2, ||/2, and !/1.

Boolean operators use short-circuit evaluation, which means that the expression on the right-hand side of the operator is only evaluated if needed.

Each of the operators has a different precedence, where not/1 is evaluated before and/2 and or/2. Brackets can be used to evaluate one part of the expression before the others:

not true and false
# => false

not (true and false)
# => true

When writing a function that returns a boolean value, it is idiomatic to end the function name with a ?. The same convention can be used for variables that store boolean values.

def either_true?(a?, b?) do
  a? or b?
end
Edit via GitHub The link opens in a new window or tab

Learn Booleans

Practicing is locked

Unlock 2 more exercises to practice Booleans