[英]How are list comprehensions implemented in Haskell?
>>=
to do this or could you use some other method for hacking a list comprehension together? 您是否必须使用do block / >>=
来执行此操作,还是可以使用其他方法将列表理解混合在一起? 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. Haskell报告中的第3.11节准确描述了列表推导的含义,以及如何将它们转换出来。
If you want monad comprehensions you basically need to replace [e]
by return e
, []
by mzero
, and concatMap
by (>>=)
in the translation. 如果你想单子推导你基本上需要更换[e]
由return e
, []
由mzero
,并concatMap
通过(>>=)
的翻译。
To augment augustss
's answer, if you have something like: 为了增加augustss
的答案,如果你有类似的东西:
[(x, y) | x <- [1..3], y <- [1..3], x + y == 4]
... it is equivalent to this use of do
notation: ......它相当于该使用do
记号:
do x <- [1..3]
y <- [1..3]
guard (x + y == 4)
return (x, y)
... which is equivalent to this use of concatMap
: ...这相当于concatMap
这种用法:
concatMap (\x ->
concatMap (\y ->
if (x + y == 4) then [(x, y)] else []
) [1..3]
) [1..3]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.