liveBook · Manning

Comprehension

As explained in Learn Haskell by Example

A list comprehension is a Haskell expression that constructs a list by evaluating an element expression over values generated and conditionally selected by its clauses.

A list comprehension constructs a list by evaluating an expression for values produced by generators and retained by guards. section 5.4.1

Use comprehensions to express common list operations directly:

  • The left side builds each result; the right side supplies generators and optional guards. section 5.4.1
  • A guard skips values that do not satisfy its condition, combining map and filter behavior. section 5.4.1
  • Multiple generators evaluate the expression over their Cartesian product. section 5.4.1
  • Pattern matching in a generator discards values whose patterns fail, as in [x | Just x <- xs]. section 5.4.1

Generating word-ladder modifications

For a word, generate modified candidates by combining every replacement letter with every word position: modified = [x : delete y word | x <- ['a' .. 'z'], y <- word, x /= y] The generators provide replacement letters and existing characters; the guard prevents reusing the removed character. section 5.4.1

ghci> [ (x, y) | x <- [1,2], y <- ['a', 'b', 'c']] :: [(Int, Char)]
[(1,'a'),(1,'b'),(1,'c'),(2,'a'),(2,'b'),(2,'c')]

Inspect a two-generator comprehension to see its Cartesian-product output. section 5.4.1

How Learn Haskell by Example covers it

How deep it goes
Defines generators, guards, Cartesian products, and pattern matching, but does not discuss implementation internals.
Examples
Uses arithmetic filtering, Cartesian-product pairs, and word insertion, deletion, and replacement candidates.
What you can do after
Builds concise Haskell list transformations with generators, guards, and multiple input lists.
How it connects
Connects list comprehensions with map, filter, Cartesian product, pattern matching, and concatMap.

Also explained in

Compare how 6 books explain comprehension →

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.