无法匹配预期类型`[([Char],a0)]'与实际类型`([Char],t0)'Haskell

 Mr尘世美_925 发布于 2023-01-04 12:29

我开始用haskell编程.我正在开发的程序只是将一个列表的总和与两个元素相加,例如:

[("book",10),("cookies",2),("icecream",5)]

这应该返回"17".这是我的代码:

total [] = []
total ([("c",e)]:y) = total y ++ [e]

但是在GHCi中运行它会给我这个错误:

:80:8:
    Couldn't match expected type `[([Char], a0)]'
                with actual type `([Char], t0)'
    In the expression: ("livro", 10)
    In the first argument of `total', namely
      `[("livro", 10), ("bolachas", 2), ("gelado", 5)]'
    In the expression:
      total [("livro", 10), ("bolachas", 2), ("gelado", 5)]

:80:21:
    Couldn't match expected type `[([Char], a0)]'
                with actual type `([Char], t1)'
    In the expression: ("bolachas", 2)
    In the first argument of `total', namely
      `[("livro", 10), ("bolachas", 2), ("gelado", 5)]'
    In the expression:
      total [("livro", 10), ("bolachas", 2), ("gelado", 5)]

:80:36:
    Couldn't match expected type `[([Char], a0)]'
                with actual type `([Char], t2)'
    In the expression: ("gelado", 5)
    In the first argument of `total', namely
      `[("livro", 10), ("bolachas", 2), ("gelado", 5)]'
    In the expression:
      total [("livro", 10), ("bolachas", 2), ("gelado", 5)]

这可能很简单,但作为初学者,我无法解决这个问题.

1 个回答
  • 在线:

    total ([("c",e)]:y) = total y ++ [e]
    

    ([("c",e)]:y)没有做你想要的.它匹配一个非空列表,其中第一个元素也是一个列表(因为[...]),并且该子列表中只有一个元素,即第一个元素等于的对"c".为了匹配你想要的东西,你需要写:

    total ((c,e):y) = total y ++ [e]
    

    但是,这仍然无法执行您想要的操作,因为它构造了输入列表中所有e值的列表.要将它们相加,您需要:

    total [] = 0
    total ((c,e):y) = total y + e
    

    2023-01-04 12:30 回答
撰写答案
今天,你开发时遇到什么问题呢?
立即提问
热门标签
PHP1.CN | 中国最专业的PHP中文社区 | PNG素材下载 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有