[英]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.