我创建了一种数据类型,用于存储有关一组人的信息:他们的姓名和出生日期。数据类型只是两个3元组列表,第一个列表包含名称session['counter']
,第二个列表包含DOB(日,月,年)。你可以看到下面的数据类型(我省略了DOB类型,因为它与这个问题无关):
(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") : []
现在,根据我对Haskell的了解,我认为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") : []
只是String
。所以我认为我的代码可以正常工作,但它让我感到非常难过。
答案 0 :(得分: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")]
答案 1 :(得分: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")])