Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 487
planarian Avatar asked Nov 27 '25 20:11

planarian


2 Answers

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.

like image 126
Daniel Wagner Avatar answered Nov 29 '25 19:11

Daniel Wagner


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.
like image 23
hdgarrood Avatar answered Nov 29 '25 20:11

hdgarrood