[英]understanding data type in haskell
I am a haskell new bee. 我是haskell新蜜蜂。 I can't just wrap my head around what is going on here
我不能只是围绕着这里发生的事情
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)`
it gives me error 它给我错误
Couldn't match expected type Either String (NestedList a)' with actual type
NestedList a' In the return type of a call of List' In the expression: List (a ++ b) In an equation for
append': 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)。
But data NestedList a=Elem a | List [NestedList a]
但是
data NestedList a=Elem a | List [NestedList a]
data NestedList a=Elem a | List [NestedList a]
doesn't it mean that NestedList
is of type Elem
or List
of NestedList
and data NestedList a=Elem a | List [NestedList a]
并不意味着NestedList
的类型为Elem
或of NestedList
List
和
append::NestedList a->NestedList a->Either String (NestedList a)
that append can return either String
or NestedList
. 该追加可以返回
String
或NestedList
。 Now when I do List(a++b)
I am returning List
. 现在当我执行
List(a++b)
我将返回List
。 It should work isn't it? 它应该工作不是吗?
My other function flatten 我的其他功能扁平化
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 [])=[]
works fine while its input parameter is also NestedList
but ghc is fine with flatten
(List(x:xs))
where List(x:xs)
is also just List
. 虽然输入参数也是
NestedList
但工作正常,但ghc可以与flatten
(List(x:xs))
,其中List(x:xs)
也是List
。 why doesn't it complain here? 为什么在这里不抱怨? Any inputs?
有输入吗?
In order to return Either ab
, you have to use either Left y
or Right x
, where y :: a
and x :: b
. 为了返回
Either ab
,必须使用Left y
或Right x
,其中y :: a
和x :: b
。 You correctly used Left "...."
and Right
in all but the last pattern: 您在最后一个模式中正确地使用了
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.