【问题标题】:Couldn't match expected type 'x' with actual type `([Char], [Char], [Char])'无法将预期类型 'x' 与实际类型 `([Char], [Char], [Char])' 匹配
【发布时间】:2017-08-26 17:41:16
【问题描述】:

我创建了一种数据类型,用于存储有关一组人的信息:他们的姓名和出生日期。数据类型只是两个三元组列表,第一个列表包含名称(first, middle, last),第二个包含 DOB(日、月、年)。你可以看到下面的数据类型(我省略了 DOB 类型,因为它与这个问题无关):

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]。所以我认为我的代码可以正常工作,但它让我非常难过。

【问题讨论】:

    标签: haskell


    【解决方案1】:

    : 运算符的优先级低于应用 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")]
    

    【讨论】:

      【解决方案2】:

      你的代码有两个问题。

      第一个是,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")])
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-06-08
        • 2014-08-30
        • 1970-01-01
        • 1970-01-01
        • 2019-04-23
        • 1970-01-01
        • 1970-01-01
        • 2022-01-23
        相关资源
        最近更新 更多