2017-08-26 82 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")] 
相关问题