2014-05-02 82 views
4

我是一个新望哈斯克尔,并有这段代码:哈斯克尔错误:无法匹配类型“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的不同类型的变量。这里有什么问题?

+0

你的问题是使用'joinLists','a''是'ELEM B'但'xs'是'[Elem a]'。 monad绑定是'(>> =):: Monad m => ma - >(a - > mb) - > mb' – josejuan

+0

@josejuan a'类型为'NestedList a = List [Elem a]'且正确, 'xs'是'[Elem a]或[NestedList a]'。 joinLists需要NestedList a和[NestedList a],所以它不应该导致问题。我怎样才能把'[Elem a]变成[Elem b]'? –

+0

@AidasSimkus'f'的类型为'(a - > m b)',这就是类型变量'b'的来源。 –

回答

2

仅供参考,这里是NestedList的工作monad实例。核实这一事例是否符合单子法应该不是很困难。

import Control.Monad 

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

instance Monad NestedList where 
    return x = Elem x 
    (Elem x) >>= f = f x 
    (List xs) >>= f = List $ map step xs 
     where step (Elem a) = f a 
       step lst = lst >>= f 

这是一个测试程序:

import Control.Monad 

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

instance Monad NestedList where 
    return x = Elem x 
    (Elem x)  >>= f = f x 
    (List xs) >>= f = List $ map step xs 
        where step (Elem a) = f a 
              step lst = lst >>= f 


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


add :: (Num a) => a -> a -> NestedList a 
add a e = Elem $ a + e 


main = do let a = Elem 1 >>= double 
          let b = List [Elem 1, Elem 2] >>= double 
          let c = List [Elem 2,List [Elem 3,Elem 4],Elem 5] >>= add 1 
          print a 
          print b 
          print c 

,其输出:

$ runhaskell t.hs 
List [Elem 1,Elem 1] 
List [List [Elem 1,Elem 1],List [Elem 2,Elem 2]] 
List [Elem 3,List [Elem 4,Elem 5],Elem 6] 
+0

谢谢!这就是我想要完成的事情。 –

7

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

但哈斯克尔在

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

坚持对我来说,它看起来像有实现你的单子要什么没有什么好办法。

更深层的原因是您想要修改“容器”的结构,而不是以容器特定的方式对“元素”进行操作。