简体   繁体   中英

How are list comprehensions implemented in Haskell?

  • 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, ie a form for the return values, lists to crunch together, and a predicate or multiple predicates.

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.

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]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM