Elixir represents true and false values with the boolean type. There are only two values: true
and false
. These values can be bound to a variable:
true_variable = true
false_variable = false
We can evaluate strict boolean expressions using the and/2
, or/2
, and not/1
operators.
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
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
In this exercise, you need to translate some rules from the classic game Pac-Man into Elixir functions.
You have four rules to translate, all related to the game states.
Don't worry about how the arguments are derived, just focus on combining the arguments to return the intended result.
Define the Rules.eat_ghost?/2
function that takes two arguments (if Pac-Man has a power pellet active and if Pac-Man is touching a ghost) and returns a boolean value if Pac-Man is able to eat the ghost. The function should return true only if Pac-Man has a power pellet active and is touching a ghost.
Rules.eat_ghost?(false, true)
# => false
Define the Rules.score?/2
function that takes two arguments (if Pac-Man is touching a power pellet and if Pac-Man is touching a dot) and returns a boolean value if Pac-Man scored. The function should return true if Pac-Man is touching a power pellet or a dot.
Rules.score?(true, true)
# => true
Define the Rules.lose?/2
function that takes two arguments (if Pac-Man has a power pellet active and if Pac-Man is touching a ghost) and returns a boolean value if Pac-Man loses. The function should return true if Pac-Man is touching a ghost and does not have a power pellet active.
Rules.lose?(false, true)
# => true
Define the Rules.win?/3
function that takes three arguments (if Pac-Man has eaten all of the dots, if Pac-Man has a power pellet active, and if Pac-Man is touching a ghost) and returns a boolean value if Pac-Man wins. The function should return true if Pac-Man has eaten all of the dots and has not lost based on the arguments defined in part 3.
Rules.win?(false, true, false)
# => false
Sign up to Exercism to learn and master Elixir with 57 concepts, 159 exercises, and real human mentoring, all for free.