【发布时间】:2019-10-31 12:03:32
【问题描述】:
我正在尝试使用 Haskell 对变量进行舍入。
r :: Double -> Double
r x = round (x)
试图编译这个,我得到以下错误
没有因使用“round”而产生 (Integral Double) 的实例
我该如何解决这个问题?谢谢!
【问题讨论】:
标签: haskell double rounding integral
我正在尝试使用 Haskell 对变量进行舍入。
r :: Double -> Double
r x = round (x)
试图编译这个,我得到以下错误
没有因使用“round”而产生 (Integral Double) 的实例
我该如何解决这个问题?谢谢!
【问题讨论】:
标签: haskell double rounding integral
这是合乎逻辑的,因为作为Integral 实例的类型,嗯...,通常是“整数”。因此,这意味着它的行为类似于Integer。 Integral 的示例有 Integer、Int、Word8 等。如错误所述,Float、Double 等不是整数。
您可以使用fromIntegral :; (Num b, Integral a) => a -> b 将Integral 类型的内容转换为Numerical 类型:
r :: Double -> Double
r = fromIntegral . round
例如:
Prelude> r 14.25
14.0
【讨论】:
Double 是许多类型类的实例:Enum、Num、Eq、Floating 等。因此fromIntegral 将专门用于Double。您收到相同错误的事实表明,在其他地方存在另一个问题,触发了相同(或非常相似)的错误消息。
r :: Double -> Double r x = round (fromIntegral(x)),我在 GHCi >GHCi,版本 8.6.5 中获得此输出:haskell.org/ghc :?寻求帮助 [1 of 1] 编译 Main (\test.hs,解释) test.hs:12:7: 错误:* 没有使用 round' * In the expression: round (fromIntegral (x)) In an equation for r' 引起的 (Integral Double) 实例:r x = round (从积分 (x)) | 12 | r x = 圆形 (fromIntegral(x)) | ^^^^^^^^^^^^^^^^^^^^^^^
fromIntegral (round x),注意我们在result上调用fromIntegral。