Search⌘ K
AI Features

Guarded Function Equations

Explore how to apply guarded equations in Haskell to write functions that respond to multiple conditions using pattern matching combined with boolean guards. Understand the syntax and execution order of guarded conditions, practice with examples like sign and fizzbuzz functions, and recognize the risks of partial functions that may cause runtime errors when not exhaustively defined.

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 ...