planarian
planarian

Reputation: 2151

translating list comprehensions to definitions using map and concat

From Thinking Functionally with Haskell, pg 67:

[...] list comprehensions are translated into equivalent definitions in
terms of map and concat. The translation rules are:

[e | True]       = [e] 
[e | q]          = [e | q, True] 
[e | b, Q]       = if b then [e | Q] else [] 
[e | p <- xs, Q] = let ok p = [e | Q]
                       ok _ = []
                   in concat (map ok xs)

The author nowhere defines e, q, Q, or b. I take it that the first means "expression," but I've never seen the others before. Could someone please enlighten me?

Upvotes: 3

Views: 305

Answers (2)

Daniel Wagner
Daniel Wagner

Reputation: 152857

This translation comes straight out of the official Haskell Report, which has this additional sentence:

where e ranges over expressions, p over patterns, l over list-valued expressions, b over boolean expressions, decls over declaration lists, q over qualifiers, and Q over sequences of qualifiers. ok is a fresh variable. The function concatMap, and boolean value True, are defined in the Prelude.

If you wonder what any of those terms means, the Report has further details.

Upvotes: 6

hdgarrood
hdgarrood

Reputation: 2151

I would guess that:

  • e is any expression, as you say
  • q is any expression with type Bool
  • b is also any expression with type Bool (this seems a bit strange, though, perhaps I'm wrong...)
  • p is any pattern. For example, Right x, Just _, x@(y,z)
  • Q is a bunch of list comprehension elements separated by commas. By "list comprehension element" I mean either guards (i.e. expressions of type Bool) or pattern matches, e.g x <- xs, Right x <- xs.

Upvotes: 3

Related Questions