我是一只新的蜜蜂。我不能只围绕这里发生的事情
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
的类型为Elem
或List
of NestedList
且
append::NestedList a->NestedList a->Either String (NestedList a)
该追加可以返回String
或NestedList
。现在当我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
。为什么不在这里抱怨?有什么输入吗?
答案 0 :(得分:4)
要返回Either a b
,您必须使用Left y
或Right x
,y :: a
和x :: 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)
-- ^^^^^