Guarded Function Equations
Explore guarded function equations, a tool that will allow us to write more interesting functions.
We'll cover the following
In the previous lesson, we learned how to write basic function equations using literal patterns and pattern variables. We will now learn how to combine pattern matching with additional conditions on the matched values.
Guarded equations
Let’s try to write a function sign :: Int -> Int
, which should return 1
when its argument is greater than 0
, and -1
when the argument is smaller than 0
. On 0
, we want the result 0
. Intuitively, it makes sense to have three equations for this, one for the "greater than 0
" case, one for the "less than 0
" case, and one for the 0
case.
We could use a literal pattern for the 0
case. However, we can cover neither of the other cases using literal patterns (as they match only single numbers) or pattern variables (as they match any number). We need a way of matching that is more general than literal patterns, but more restrictive than pattern variables.
We can solve this problem using guards on our pattern variables. Here is one way to write the function sign
:
Get hands-on with 1400+ tech skills courses.