0

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

 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 typeNestedList a' 在List' In the expression: List (a ++ b) In an equation forappend 调用的返回类型中:append (List a) (List b) = List (a ++ b)。

但这data NestedList a=Elem a | List [NestedList a]是否意味着它NestedList是类型ElemorList of NestedList

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

该 append 可以返回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))whereList(x:xs)也只是List. 为什么它不在这里抱怨?有什么输入吗?

4

1 回答 1

4

为了返回Either a b,您必须使用Left yor Right x、 wherey :: 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)
--                         ^^^^^
于 2014-01-18T17:20:36.587 回答