liveBook · Manning

Recursive definition

As explained in Learn Haskell by Example

A recursive definition is a definition that refers directly or indirectly to itself.

A recursive definition refers directly or indirectly to itself. In Haskell, it commonly combines a base case with a recursive case that processes a smaller part of the input. section 4.1.2

Numbering every line

A local function processes a list of lines. Its empty-list case returns [], while its recursive case emits the current line number and calls itself with the remaining lines and an incremented counter. Starting with 1 produces [(Just 1,"Hello"),(Just 2,""),(Just 3,"World")]. section 4.1.2

Listing 4.3 A function that numbers every line in order
numberAllLines :: [String] -> NumberedLines
numberAllLines lines =
  let go :: Int -> [String] -> NumberedLines    #1
      go _ [] = []                                   #2
      go counter (x : xs) = (Just counter, x) : go (counter + 1) xs   #3
   in go 1 lines     #4

Inspect the complete recursive definition, including its base case, recursive pattern match, counter update, and initial call. section 4.1.2

Use recursive definitions to:

  • Pattern match lists such as Strings, which are lists of characters. section 4.1.2
  • Define related helpers with additional parameters inside a let binding. section 4.1.2
  • Implement utilities such as lines, unlines, words, and unwords. section 4.1.2

How Learn Haskell by Example covers it

How deep it goes
Demonstrates base cases, pattern matching, recursive calls, counters, and local helpers, but stops short of formal recursion theory.
Examples
Uses line numbering and proposed implementations of lines, unlines, words, and unwords as concrete examples.
What it assumes
Assumes basic Haskell functions and lists while teaching recursive pattern matching through a concrete line-numbering task.
What you can do after
Apply recursive definitions to implement list-processing utilities and test their results in GHCi.
How it connects
Connects recursive definitions with pattern matching, guards, let bindings, lists, functions, and declarative programming.

Also explained in

Compare how 2 books explain recursive definition →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Haskell by Example. The section links point to the parts of the book it draws on.