HASKELL / CHAPTER 05

Structural recursion and base cases

Intermediate

Follow recursive list processing with a clear measure of progress.

By the end of this chapter

  • Define an empty-list base case
  • Recur on the tail
  • Trace accumulated results while unwinding

The idea

Enter with list patterns and function equations understood. Structural recursion follows the shape of a value. A list function can handle [] directly and handle x:xs by combining x with the result for xs. The recursive call receives a shorter finite list, which supplies a clear termination argument. State the input assumption when a function depends on finiteness.

A base case contributes an identity or boundary result, such as zero for a sum or one for a product. Choose that value from the function’s meaning rather than copying another algorithm. To trace recursion, write the pending combinations until the empty case appears, then evaluate them back outward. Not every recursive function is efficient or stack-safe for every input; this chapter establishes correct structure before discussing performance refinements.

Haskell example
sumList :: [Integer] -> Integer
sumList [] = 0
sumList (x:xs) = x + sumList xs
main = print (sumList [2,5,1])
Result
8

The expression expands to 2 + (5 + (1 + 0)). The empty list supplies the additive identity.

Try it yourself

Write a recursive product function and justify the result for the empty list.

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

CHECK YOUR UNDERSTANDING

Chapter checkpoint

Which recursive argument progresses through a finite list matched as x:xs?