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

mag*_*mig 3 int haskell char ghci

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

[("book",10),("cookies",2),("icecream",5)]
Run Code Online (Sandbox Code Playgroud)

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

total [] = []
total ([("c",e)]:y) = total y ++ [e]
Run Code Online (Sandbox Code Playgroud)

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

<interactive>: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)]

<interactive>: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)]

<interactive>: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)]
Run Code Online (Sandbox Code Playgroud)

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

jwo*_*der 6

在线:

total ([("c",e)]:y) = total y ++ [e]
Run Code Online (Sandbox Code Playgroud)

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

total ((c,e):y) = total y ++ [e]
Run Code Online (Sandbox Code Playgroud)

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

total [] = 0
total ((c,e):y) = total y + e
Run Code Online (Sandbox Code Playgroud)