2014-01-18 67 views
0

我是一個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追加的調用的返回類型': append(List a)(List b)= List(a ++ b)。

data NestedList a=Elem a | List [NestedList a]並不意味着該NestedList類型爲ElemListof NestedList

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。爲什麼不在這裏抱怨?任何投入?

+3

BTW,沒有必要爲'append'在這些混合的情況下失敗。你仍然可以返回一個'NestedList'。 – augustss

回答

5

爲了回報Either a b,您可以選擇使用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) 
--       ^^^^^