Learn By Example: Elixir guards

Here’s an easy to follow code example of how to use Elixir guards

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()
				
			

Never miss another post!

Get my latest articles delivered directly to your inbox.

Never miss another post!

Get my latest articles delivered directly to your inbox.

Upcoming Course

Break Free From Tutorials!

A software development course that doesn’t get you stuck with specifics from a tutorial, but challenges you to think like a software architect. 

🙏

Great Choice!

Thanks for enabling notifications! Don’t worry, I hate spam too and I won’t ever disclose your contact information to 3rd parties.