我创建了一种数据类型,用于存储有关一组人的信息:他们的姓名和出生日期。数据类型只是两个三元组列表,第一个列表包含名称(first, middle, last)
,第二个列表包含道布(日、月、年)。您可以看到下面的数据类型(我省略了道布类型,因为它与这个问题无关):
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]
。所以我想我的代码会很好,但这让我很困惑。
发布于 2017-08-26 01:41:16
代码中有两个问题。
首先,People
数据类型接受Names
数据类型,但是您试图用[(String,String,String)]
数据类型来填充它。
第二,正如@Koter支柱的答复中提到的,值构造函数(此处为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")])
发布于 2017-08-25 20:32:25
:
操作符的优先级低于应用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")]
https://stackoverflow.com/questions/45891910
复制相似问题