【问题标题】:Haskell - Split digits and then multiplyHaskell - 拆分数字然后相乘
【发布时间】:2020-11-20 17:32:38
【问题描述】:

基本上,我想要做的是接收一个数字,分成一个数字列表,然后将每个值加倍。

但是,我不想使用 Integer 类型,因为我可能会使用其他一些包含类型变量的函数。我试图做这样的事情:

digs :: (Integral a) => a -> [a] 
digs 0 = []
digs x = digs (x `div` 10) ++ [x `mod` 10]

double :: (Integral a) => [a] -> [a]
double xs = [x*2 | x <- xs]

这两个函数单独工作,但如果我尝试像“double digs 1234”这样的东西,它会给我一个错误。

无法将预期类型 'Integer -> t' 与实际类型 '[Integer]' 匹配

我不确定这个消息是什么意思。

【问题讨论】:

  • 你需要使用函数组合,double . digs $ 1234
  • 谢谢。有效。你能解释一下原因吗?
  • 或double $ digs 1234。甚至只使用括号:double (digs 1234)

标签: haskell


【解决方案1】:

正如 cmets 中所说,您需要组合函数。 Haskell 将double digs 1234 解释为(double digs) 1234。因此,haskell 认为您将函数 digs 作为参数传递给 double。这是我从您的示例中得到的完整错误消息:

<interactive>:3:1: error:
    • Couldn't match expected type ‘Integer -> t’
                  with actual type ‘[Integer]’
    • The function ‘double’ is applied to two arguments,
      but its type ‘[Integer] -> [Integer]’ has only one
      In the expression: double digs 1234
      In an equation for ‘it’: it = double digs 1234
    • Relevant bindings include it :: t (bound at <interactive>:3:1)

<interactive>:3:8: error:
    • Couldn't match expected type ‘[Integer]’
                  with actual type ‘Integer -> [Integer]’
    • Probable cause: ‘digs’ is applied to too few arguments
      In the first argument of ‘double’, namely ‘digs’
      In the expression: double digs 1234
      In an equation for ‘it’: it = double digs 1234

请注意第一条错误消息:“函数 double 应用于两个参数,但其类型只有一个。” Haskell 将其解读为先通过 digs 以加倍,然后通过 1234。

因此,您需要确保先将 1234 传递给 digs,然后将该结果传递给 double。我认为最适合初学者的方式是使用括号:

*Main> double (digs 1234)
[2,4,6,8]

Haskell 的函数调用风格与大多数语言有很大不同,因此需要一些时间来适应。

【讨论】:

  • 谢谢。我没有意识到这一点,我在想象它会从挖掘开始。
猜你喜欢
  • 2018-12-16
  • 1970-01-01
  • 2010-10-01
  • 1970-01-01
  • 2019-01-13
  • 1970-01-01
  • 2013-02-02
  • 2020-11-22
  • 2011-04-27
相关资源
最近更新 更多