【发布时间】:2014-03-26 14:08:52
【问题描述】:
我在Learn you a Haskell 中读到,Haskell 中的列表推导可以重写为单子连接或(实际上是相同的)do-notation。
但是,当我尝试重写以下代码时(生成所有可能的列表,其中每个元素都来自给定列表之一):
c :: [[a]] -> [[a]]
c [] = [[]]
c (x:xs) = [a:b | a <- x, b <- c xs]
以这样的方式:
d :: [[a]] -> [[a]]
d [] = [[]]
d (x:xs) = do
a <- x
b <- d xs
return a:b
我收到以下错误:
Couldn't match type `a' with [a]
`a' is a rigid type variable bound by
the type signature for d :: [[a]] -> [[a]]
Expected type: [[a]]
Actual type: [a]
In the second argument of `(:)', namely `b'
In a stmt of a 'do' block: return a : b
如果我把do的最后一行改成这样:return a:[b],我不会报错,但是结果明显不正确:
ghci> c [[1, 2], [3, 4]]
[[1,3],[1,4],[2,3],[2,4]]
ghci> d [[1, 2], [3, 4]]
[[1],[3],[1],[],[1],[4],[1],[],[2],[3],[2],[],[2],[4],[2],[]]
所以问题是:
- 如何重写此列表理解?
- 列表理解和 do-notation 是否可以互换,一般如何替换?
【问题讨论】:
标签: haskell list-comprehension do-notation