gpt4 book ai didi

haskell 错误: Couldn't match type 'a' with 'b'

转载 作者:行者123 更新时间:2023-12-02 14:41:07 24 4
gpt4 key购买 nike

我是 Haskell 的新手,有这段代码:

import Control.Monad

data NestedList a = Elem a | List [NestedList a] deriving (Show)

instance Monad NestedList where
return a = List [Elem a]
(List (Elem a: xs)) >>= f = let a' = f a in a' `joinLists` xs

func :: a -> NestedList a
func a = List ([Elem a] ++ [Elem a])

joinLists :: NestedList a -> [NestedList a] -> NestedList a
joinLists (List a) b = List (a ++ b)

main = do let a = List [Elem 1, Elem 2] >>= func
print a

我想做的是获取一个包含元素的列表,复制列表的第一个元素并向该列表添加一个尾部。因此 List [Elem 1, Elem 2] 将等于 List [Elem 1, Elem 1, Elem 2]。我知道这不是使用 Monad 的好例子,但这是为了学习。

我收到这样的错误:

Couldn't match type 'a' with 'b'
'a' is a rigid type variable bound by
the type signature for
'>>= :: NestedList a -> (a -> NestedList b) -> NestedList b
'b' is a rigid type variable bound by
the type signature for
'>>= :: NestedList a -> (a -> NestedList b) -> NestedList b
Expected type: [NestedList b]
Actual type: [NestedList a]
In the second argument of 'joinLists', namely 'xs'

我知道错误是它需要一个不同类型的 NestedList 变量。这里有什么问题吗?

最佳答案

I know that's not a good example of using Monads, but that's for the sake of learning.

具体来说,您的 >>= 实现不够通用。您给出的内容类型为:

List a -> (a -> List a) -> List a

但 haskell 坚持

List a -> (a -> List b) -> List b

对我来说,似乎没有什么好方法可以在 monad 中实现您想要的目标。

更深层次的原因是你想要修改“容器”的结构,而不是以容器特定的方式对“元素”做一些事情。

关于 haskell 错误: Couldn't match type 'a' with 'b' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23425853/

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