了解haskell中的数据类型

时间:2014-01-18 17:16:47

标签: haskell either

我是一只新的蜜蜂。我不能只围绕这里发生的事情

 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 a'     在List' In the expression: List (a ++ b) In an equation for追加'的回复类型中:         追加(列表a)(列表b)=列表(a ++ b)。

data NestedList a=Elem a | List [NestedList a]并不意味着NestedList的类型为ElemList of 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。为什么不在这里抱怨?有什么输入吗?

1 个答案:

答案 0 :(得分:4)

要返回Either a b,您必须使用Left yRight xy :: 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)
--                         ^^^^^