[英]understanding data type in 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
追加”:追加(列表a)(列表b)=列表(a ++ b)。
但是data NestedList a=Elem a | List [NestedList a]
data NestedList a=Elem a | List [NestedList a]
并不意味着NestedList
的类型为Elem
或of NestedList
List
和
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
。 为什么在这里不抱怨? 有输入吗?
为了返回Either ab
,必须使用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)
-- ^^^^^
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.