2017-08-26 84 views
0

我創建了一種數據類型來存儲有關一組人的信息:出生日期。數據類型只是兩個三元組列表,第一個列表包含名稱(first, middle, last),第二個列表包含DOB(日,月,年)。你可以看到下面的數據類型(我省略了DOB類型,因爲它是不相關的這個問題):無法與實際類型'([Char],[Char],[Char])匹配預期類型'x''

data Names = Names [(String, String, String)] 
data People = People Names 

我想要編寫創建初始列表的功能,因此它返回的名稱第一個人,然後列表People。這是迄今爲止:

initiallist :: ([String], People) 
initiallist = (first_name, all_people) 
    where first_name = "Bob" : "Alice" : "George" : [] 
     all_people = People ("Bob","Alice","George") : [] 

這導致

error: 
* Couldn't match expected type `Names' 
    with actual type `([Char], [Char], [Char])' 
* In the first argument of `People', namely `("Bob", "Alice", "George")' 
    In the first argument of `(:)', namely 
    `People ("Bob", "Alice", "George")' 
    In the expression: People ("Bob", "Alice", "George") : [] 

現在,在我的Haskell的知識,我認爲String只是一個[Char]。所以我覺得我的代碼可以正常工作,但它讓我絕對難住。

回答

1

代碼中有兩個問題。

首先是,People數據類型接受Names數據類型,但您試圖用[(String,String,String)]數據類型爲其提供數據類型。

二是,如@ Koterpillar的回答(這裏People和/或Names)中提到的價值構造的優先級比列表值構造:(左協會)更高。

另一點是您的數據類型可以通過newtype來定義,從而生成更高效的代碼。因此,通過記住值構造函數也是函數,如果你想用:構造函數來創建你的列表,你可能會喜歡這樣做;如果你想使用:構造函數來創建你的列表,你可能會喜歡;如果你想使用:構造函數來創建你的列表,

newtype Names = Names [(String, String, String)] 
newtype People = People Names 

initiallist :: ([String], People) 
initiallist = (first_name, all_people) 
    where first_name = "Bob" : "Alice" : "George" : [] 
      all_people = People $ Names $ ("Bob","Alice","George") : [] 

或當然,你可以優選不喜歡

all_people = People (Names [("Bob","Alice","George")]) 
3

:運算符的優先級低於應用People構造函數的優先級。所以,你的表情居然是:

all_people = (People ("Bob","Alice","George")) : [] 

它是在錯誤消息指出,說什麼也People構造適用於:

...first argument of `People', namely `("Bob", "Alice", "George")' 

你將不得不使其明確:

all_people = People (("Bob","Alice","George")) : []) 

或者,使用列表符號:

all_people = People [("Bob","Alice","George")] 
相關問題