liveBook · Manning

Generator

As explained in Learn Haskell by Example

A generator is a list-comprehension clause that supplies values from a list or other sequence for subsequent comprehension clauses.

A generator is the list-comprehension clause that supplies values for the expression on the left. The expression is evaluated for every generated value that satisfies the guards. section 5.4.1

Generate and filter values

[x + 1 | x <- [1..10], x <= 5] produces [2,3,4,5,6]. The generator supplies x from [1..10], while the guard keeps only values through 5. section 5.4.1

Generators support several useful list-comprehension patterns:

  • Multiple generators combine their values using a Cartesian product, so each left-hand expression runs for every combination. section 5.4.1
  • Generators can construct practical candidate lists, such as adding, removing, or modifying letters in a word. section 5.4.1
  • A pattern in a generator can filter values: a failing match skips the value, as in [x | Just x <- xs]. section 5.4.1
ghci> [ x + 1 | x <- [1..10] ] :: [Int]
[2,3,4,5,6,7,8,9,10,11]
ghci> [ x + 1 | x <- [1..10], x <= 5 ] :: [Int]
[2,3,4,5,6]

Interactive examples show a generator supplying values and a guard restricting which generated values reach the result. section 5.4.1

How Learn Haskell by Example covers it

How deep it goes
Explains generator evaluation, guards, Cartesian products, and pattern matching without descending into implementation internals.
Examples
Uses numeric ranges, Cartesian products, word transformations, and Maybe-pattern filtering as concrete examples.
What you can do after
Builds filtered and combined lists with generators, guards, multiple sources, and matching patterns.
How it connects
Connects generators with list comprehensions, guards, map, filter, Cartesian products, and pattern matching.

Also explained in

Compare how 12 books explain generator →

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.