【问题标题】:Couldn't match `[Int]' with `Integer -> Int' but works in GHCI无法将 `[Int]' 与 `Integer -> Int' 匹配,但在 GHCI 中有效
【发布时间】:2017-01-17 20:15:22
【问题描述】:

我是 Haskell 的新手,所以这个问题对大多数 Haskell 程序员来说应该是微不足道的: 我有一个函数digits :: Integer -> [Int],它将整数转换为其数字列表(123 到 [1,2,3])。现在要获得这些数字的总和,我在 ghci 中输入 sum $ digits 123 并且一切正常,它输出 6。但是,只要我在文件中创建如下函数,就会出现错误。这可能与 ghci 推断 123 的类型有关,但这还不够,我可以解决问题。

文本文件中的函数:

digitalSum :: Integer -> Int
digitalSum = sum $ digits

和错误:

* Couldn't match type `[Int]' with `Integer -> Int'
  Expected type: Integer -> Integer -> Int
    Actual type: Integer -> [Int]
* In the second argument of `($)', namely `digits'
  In the expression: sum $ digits
  In an equation for `digitalSum': digitalSum = sum $ digits

【问题讨论】:

标签: haskell


【解决方案1】:

虽然sum $ digits 123 在 GHCi 中工作(就像在 Haskell 文件中一样),但 sum $ digits(也可以写成 sum digits)在 GHCi 中也不起作用。

问题是sum 接受一个数字列表,但digits 不是一个列表,它是一个函数。

您想要digitalSum x = sum $ digits xdigitalSum = sum . digits。这里. 是函数组合运算符,它从两个现有函数中创建一个函数(与$ 相反,$ 接受一个函数及其参数,而不是另一个函数)。

【讨论】:

    【解决方案2】:

    你忘记了论据

    digitalSum :: Integer -> Int
    digitalSum x = sum $ digits x
    

    或者,您可以使用函数组合

    digitalSum :: Integer -> Int
    digitalSum = sum . digits
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-29
      • 1970-01-01
      • 2011-12-19
      • 2014-04-26
      相关资源
      最近更新 更多