Another rare feature that Elixir has are guards. Guards can be used to make functions conditional, based on its parameters. This allows a precondition to be first met before the function is even called. This is similar in concept to the Eiffel programming language which predicates itself around the design by contract paradigm.
Here’s an example:
defmodule AgeGroup do
def check(age) when age >= 0 and age <= 0.99 do
:baby
end
def check(age) when age >= 1 and age <= 2.99 do
:toddler
end
def check(age) when age >= 3 and age <= 4.99 do
:preschooler
end
def check(age) when age >= 5 and age <= 11.99 do
:gradeschooler
end
def check(age) when age >= 12 and age <= 17.99 do
:teen
end
def check(age) when age >= 18 and age <= 24 do
:young_adult
end
def check(age) when age >= 25 and age <= 64 do
:adult
end
def check(age) when age >= 65 do
:senior
end
end
defmodule Main do
def main do
IO.inspect(AgeGroup.check(0.5), label: "Age group for 6 month old")
# Age group for 6 month old: :baby
IO.inspect(AgeGroup.check(2) , label: "Age group for 2 year old")
# Age group for 2 year old: :toddler
IO.inspect(AgeGroup.check(4) , label: "Age group for 4 year old")
# Age group for 4 year old: :preschooler
IO.inspect(AgeGroup.check(8) , label: "Age group for 8 year old")
# Age group for 8 year old: :gradeschooler
IO.inspect(AgeGroup.check(13) , label: "Age group for 13 year old")
# Age group for 13 year old: :teen
IO.inspect(AgeGroup.check(18) , label: "Age group for 18 year old")
# Age group for 18 year old: :young_adult
IO.inspect(AgeGroup.check(26) , label: "Age group for 26 year old")
# Age group for 26 year old: :adult
IO.inspect(AgeGroup.check(46) , label: "Age group for 46 year old")
# Age group for 46 year old: :adult
IO.inspect(AgeGroup.check(67) , label: "Age group for 67 year old")
# Age group for 67 year old: :senior
end
end
Main.main()