我是一个新望哈斯克尔,并有这段代码:哈斯克尔错误:无法匹配类型“A”与“B”
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
我所试图做的是要接受列表使用元素,复制列表的第一个元素并向此列表添加尾部。因此,列表[Elem 1,Elem 2]将等于列表[Elem 1,Elem 1,Elem 2]。我知道这不是一个使用Monads的好例子,但那是为了学习。
我得到这样的错误:
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的不同类型的变量。这里有什么问题?
你的问题是使用'joinLists','a''是'ELEM B'但'xs'是'[Elem a]'。 monad绑定是'(>> =):: Monad m => ma - >(a - > mb) - > mb' – josejuan
@josejuan a'类型为'NestedList a = List [Elem a]'且正确, 'xs'是'[Elem a]或[NestedList a]'。 joinLists需要NestedList a和[NestedList a],所以它不应该导致问题。我怎样才能把'[Elem a]变成[Elem b]'? –
@AidasSimkus'f'的类型为'(a - > m b)',这就是类型变量'b'的来源。 –