2014-01-18 59 views
0

我是一个haskell新的蜜蜂。我不能换我围​​绕这到底是怎么回事了解haskell的数据类型

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

append::NestedList a->NestedList a->Either String (NestedList a) 
append (Elem x) (Elem y) = Right $ List [Elem x, Elem y] 
append (_) (Elem _)=Left "Elements are not allowed" 
append (Elem _) (_)=Left "Elements are not allowed" 
append (List a) (List b)=List(a++b)` 

它给了我的头错误

无法比拟预期型Either String (NestedList a)' with actual type NestedList一个” 在List' In the expression: List (a ++ b) In an equation for追加的调用的返回类型': append(List a)(List b)= List(a ++ b)。

data NestedList a=Elem a | List [NestedList a]并不意味着该NestedList类型为ElemListof NestedList

append::NestedList a->NestedList a->Either String (NestedList a) 

是追加可以返回StringNestedList。现在,当我做List(a++b)我正在返回List。它应该工作不是吗?

我的其他功能扁平化

flatten ::NestedList a->[a] 
flatten (Elem x)=[x] 
flatten (List(x:xs))=flatten(x)++flatten(List xs) 
--flatten NestedList (x:xs)=flatten(x)++flatten(List xs) 
flatten(List [])=[] 

正常工作,而它的输入参数也是NestedList但GHC是细跟flatten(List(x:xs))其中List(x:xs)也只是List。为什么不在这里抱怨?任何投入?

+3

BTW,没有必要为'append'在这些混合的情况下失败。你仍然可以返回一个'NestedList'。 – augustss

回答

5

为了回报Either a b,您可以选择使用Left yRight x,其中y :: ax :: b。您正确使用所有Left "...."Right,但最后的模式:

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

append::NestedList a->NestedList a->Either String (NestedList a) 
append (Elem x) (Elem y) = Right $ List [Elem x, Elem y] 
append (_) (Elem _)  = Left $ "Elements are not allowed" 
append (Elem _) (_)  = Left $ "Elements are not allowed" 
append (List a) (List b) = Right $ List(a++b) 
--       ^^^^^