Guard Clauses In Case Statements

It is a fairly common practice to use guard clauses in function definitions. Elixir also allows guard clauses to be used in case statements. Not only can you use the standard pattern matching that you are used to, but you can also include a when clause to check more specific details about the subject of the case statement.

For example, let's look at this Integer module that tells us what type of integer we are dealing with:

defmodule Integer do  
  def type(int) do
    case int do
      int when int < 0 -> "negative"
      0                -> "zero"
      int when int > 0 -> "positive"
    end
  end
end  

If we try invoking Integer.type/1 with different integer values, we can see the guard clauses taking affect.

> Integer.type(0)
"zero"
> Integer.type(-3)
"negative"
> Integer.type(77)
"positive"

I discovered and utilized this feature of case statements when working on a recent project.

Elixir is a flexible language. We can use guard clauses in both function definitions and case statements.