我可以在这个表达式中取消对列表理解的糖化:
Can I unsugar list comprehension in this expression:
[(i,j) | i <- [1..4], j <- [i+1..4]]这是输出:
[(1,2),(1,3),(1,4),(2,3),(2,4),(3,4)]我怎样才能用 map、filter 等写出那段代码?
How can I, with map, filter and so on, write that piece of code?
编辑
这里是另一个:
[(i,j,k) | i <- [1..6], j <- [i+1..6],k <- [j+1..6]]这是输出:
[(1,2,3),(1,2,4),(1,2,5),(1,2,6),(1,3,4),(1,3,5),(1,3,6),(1,4,5),(1,4,6),(1,5,6),(2,3,4),(2,3,5),(2,3,6),(2,4,5),(2,4,6),(2,5,6),(3,4,5),(3,4,6),(3,5,6),(4,5,6)] 推荐答案列表推导式(实际上是 Monad 推导式)可以脱糖为 do 表示法.
List comprehensions (in fact, Monad comprehensions) can be desugared into do notation.
do i <- [1..4] j <- [i+1..4] return (i,j)可以像往常一样脱糖:
[1..4] >>= i -> [i+1..4] >>= j -> return (i,j)众所周知,a >>= x ->return b 与 fmap (x -> b) a 相同.所以中间脱糖步骤:
It is well known that a >>= x -> return b is the same as fmap (x -> b) a. So an intermediate desugaring step:
[1..4] >>= i -> fmap (j -> (i,j)) [i+1..4]对于列表,(>>=) = flip concatMap 和 fmap = map
(flip concatMap) [1..4] (i -> map (j -> (i,j) [i+1..4])flip 只是切换输入的顺序.
flip simply switches the order of the inputs.
concatMap (i -> map (j -> (i,j)) [i+1..4]) [1..4]这就是你最终得到 Tsuyoshi 答案的方式.
And this is how you wind up with Tsuyoshi's answer.
第二个可以类似地脱糖为:
The second can similarly be desugared into:
concatMap (i -> concatMap (j -> map (k -> (i,j,k)) [j+1..6]) [i+1..6]) [1..6]更多推荐
删除语法糖:Haskell 中的列表理解
发布评论