HASKELL / CHAPTER 03

Patterns and guards

Intermediate

Describe alternatives with ordered equations and explicit conditions.

By the end of this chapter

  • Match data constructors and list shapes
  • Use guards for conditions
  • Provide complete cases

The idea

Enter with function signatures and application understood. Pattern matching decomposes values by their structure. The pattern [] matches an empty list, while x:xs matches a nonempty list with head x and remaining tail xs. Function equations are tried in order, so an earlier general pattern can make a later special case unreachable. Cover the cases that the function’s advertised inputs allow.

Guards refine an equation using boolean conditions. They are checked in order, and otherwise supplies a conventional final true condition. Keep a guard focused on a property of already matched values instead of forcing every decision into nested conditionals. A complete function handles boundaries deliberately, including zero and empty input when applicable. Missing cases can fail at runtime when the uncovered value is demanded.

Haskell example
label :: Integer -> String
label n
  | n < 0 = "negative"
  | n == 0 = "zero"
  | otherwise = "positive"
main = putStrLn (label 0)
Result
zero

The negative guard fails, the equality guard succeeds, and the remaining guard is not selected.

Try it yourself

Write a function that labels a list empty or nonempty using two pattern equations.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

Which list shape matches x:xs?