Elixir: Module: Guard
In the code example above, the when
keyword is used to evaluate each expression to prevent a negative value (or bad argument) from being passed to the :math
module’s sqrt()
function. For example, passing the value -1
to :math.sqrt()
would return a FunctionClauseError
because a function clause that would work with a negative argument would not be found. And execution breaks, before continuing to :math.sqrt(2 * 9.8 * distance)
. Passing a negative number—without a guard—would otherwise return an ArithmeticError
. So (as demonstrated both above and below), when
is used as an Elixir guard to prevent a negative number from being passed to the :math.sqrt()
function.
iex(1)> Drop.fall_velocity(:earth, -1)
** (FunctionClauseError) no function clause matching in Drop.fall_velocity/2
drop.ex:2: Drop.fall_velocity(:earth, -1)
iex(2)> Drop.fall_velocity(:earth, 23)
21.23205124334434
iex(3)> Drop.fall_velocity(:earth, 0)
0.0