簡體   English   中英

了解Haskell中的數據類型

[英]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的類型為Elemof NestedList List

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

該追加可以返回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)) ,其中List(x:xs)也是List 為什么在這里不抱怨? 有輸入嗎?

為了返回Either ab ,必須使用Left yRight x ,其中y :: 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)
--                         ^^^^^

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM