liveBook · Manning

List constructor

As explained in Learn Haskell by Example

A list constructor is a Haskell constructor that builds a list either as the empty list or by prepending an element to an existing list.

A list constructor builds a list. Haskell lists have two constructors: [] creates the empty list, while (:) prepends an element to an existing list. section 2.4.1

The two constructors describe every list:

  • [] represents the empty list. section 2.4.1
  • (x : xs) represents a nonempty list, with x as its head and xs as its tail. section 2.4.1

Constructing lists

The expression 1 : [2, 3] produces [1,2,3]. Chaining the constructor, 1 : 2 : 3 : [], produces the same list. section 2.4.1

Using constructors in patterns

Pattern matching can define behavior for both list shapes: listLength [] = 0 and listLength (x : xs) = 1 + listLength xs. These patterns are exhaustive for lists. section 2.4.1

ghci> []
[]
ghci> 1 : []
[1]
ghci> 1 : [2, 3]
[1,2,3]
ghci> 1 : 2 : 3 : []
[1,2,3]

Inspect interactive examples of [] and (:) building lists. section 2.4.1

How Learn Haskell by Example covers it

How deep it goes
Explains both constructors, head-and-tail decomposition, list construction, and exhaustive recursive patterns.
Examples
Demonstrates [], (:), chained construction, listLength, and indexOf through Haskell expressions and definitions.
What it assumes
Teaches [] and (:) before using them to distinguish empty lists from lists with a head and tail.
What you can do after
Apply list constructors via pattern matching to define recursive functions over empty and nonempty lists.
How it connects
Connects list constructors with pattern matching, recursion, head, tail, and exhaustive function definitions.

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.