gpt4 book ai didi

haskell - 用do-notation重写haskell列表理解

转载 作者:行者123 更新时间:2023-12-04 13:19:22 25 4
gpt4 key购买 nike

我已阅读 Learn you a Haskell ,Haskell 中的列表推导可以重写为 monadic join 或(实际上是相同的)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 是否可以互换,一般如何替换?
  • 最佳答案

    仔细查看错误信息:

    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

    This means that it was parsed as

    (return a) : b

    因此 b成为 (:) 的第二个参数那里;但你打算这样做
    return (a : b)

    关于haskell - 用do-notation重写haskell列表理解,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21995789/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com