Question

  • Are list comprehensions simply a language feature?
  • What's the easiest way to fake a list comprehension using pure Haskell?
  • Do you have to use a do block/>>= to do this or could you use some other method for hacking a list comprehension together?

Clarification: By "fake" a list comprehension I mean create a function that takes the same input and produces the same input, i.e. a form for the return values, lists to crunch together, and a predicate or multiple predicates.

Was it helpful?

Solution

Section 3.11 in the Haskell report describes exactly what list comprehensions mean, and how to translate them away.

If you want monad comprehensions you basically need to replace [e] by return e, [] by mzero, and concatMap by (>>=) in the translation.

OTHER TIPS

To augment augustss's answer, if you have something like:

[(x, y) | x <- [1..3], y <- [1..3], x + y == 4]

... it is equivalent to this use of do notation:

do x <- [1..3]
   y <- [1..3]
   guard (x + y == 4)
   return (x, y)

... which is equivalent to this use of concatMap:

concatMap (\x ->
    concatMap (\y ->
        if (x + y == 4) then [(x, y)] else []
        ) [1..3]
    ) [1..3]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top