How are list comprehensions implemented in Haskell?

心已入冬 提交于 2021-01-27 03:51:30

问题


  • 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.


回答1:


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.




回答2:


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]


来源:https://stackoverflow.com/questions/20687896/how-are-list-comprehensions-implemented-in-haskell

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!