【问题标题】:What causes a type error like this in Haskell?是什么导致 Haskell 中出现这样的类型错误?
【发布时间】:2016-06-17 09:27:58
【问题描述】:

我正在使用 Haskell 来评估值表的简单限制。我定义了以下函数:

f :: (Integral a) => a -> a
f x = div 1 $ subtract 6 x

在 GHCI 中,我 let leftSide = [5.90, 5.91..5.99]let rightSide = [6.10,6.09..6.01],然后:

GHCI> map f leftSide

这会导致这个错误:

<interactive>:50:5
  No instance for (Integral Double) arising from a use of `f'
  Possible fix: add an instance declaration for (Integral Double)
  In the first argument of `map', namely `f'
  In the expression: map f leftSide
  In an equation for `it': it = map f leftSide

将我的 f 类型声明更改为 (Integral Double a) =&gt; a -&gt; a 会使编译器抱怨“Integral”如何应用于太多类型参数。这是怎么回事?

【问题讨论】:

  • 可能是因为Double 不是积分?

标签: haskell typeerror


【解决方案1】:

我认为你只是尝试了错误的部门 - 你真的想要(/) 而不是div...

您的问题是 div 需要 Integral 类型(例如 Integer):

Prelude> :t div
div :: Integral a => a -> a -> a

但随后您将其与Fractional (6.10, ...) 一起使用,通过maping 它覆盖您的leftSiderightSide

现在 GHCi 将其默认为 Double - 但 Double 不是 Integral 的实例 - 这正是 Haskell 所抱怨的。


你尝试的东西不起作用,我猜你想写 (Integral a, Double a) =&gt; ... 但最后(如果它会起作用 - 它不会因为 Double 是类型而不是类型类)它会是就像说f :: Double -&gt; Double 一样——这会让你再次出错(因为Double 没有div

简而言之:使用(/) 而不是div,它应该可以工作:

f :: Fractional r => r -> r
f x = (1 /) $ subtract 6 x

这是你的第一个例子:

Prelude> let leftSide = [5.90, 5.91..5.99]
Prelude> map f leftSide
[-10.000000000000036,-11.111111111111128
,-12.49999999999999,-14.285714285714228
,-16.66666666666653,-19.999999999999716
,-24.999999999999424,-33.33333333333207
,-49.999999999996625,-99.99999999998437]

顺便说一句:如果你使用无点,你可以让这个更短

f = (1 /) . (6 -)

如果你把它写出来,或者更干净/更易读

f x = 1 / (6 - x)

【讨论】:

  • div 1 不应该变成(1 /)(或者更好的是,recip)吗?
  • doh ...当然(实际上我应该只是复制和粘贴-正如您所见,我在 GHCi 中使用的 sn-p 使用了正确的定义:( ...
  • for me recipsubtract 有同样的问题 - 如果你进行计算,IMO 数学风格的公式比 拼写 更清晰出来了-但这只是我的口味
  • @Carsten:你这是什么意思?我想说subtract 只是一个丑陋的解决方法,因为它无法编写- 的正确部分。 OTOH,negaterecip 实际上捕捉了逆元素的数学概念,这在某种意义上比 a/ba-b 更基本。
  • @leftaroundabout 我说的是这里的情况——我发现1 / (6-x)recip . subtract 6自然,我也更喜欢(1 /) 而不是recip——但是正如我所说,这只是我的口味
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-12-01
  • 1970-01-01
  • 2011-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多