【问题标题】:Haskell No instance for Integral DoubleHaskell 没有 Integral Double 的实例
【发布时间】:2019-10-31 12:03:32
【问题描述】:

我正在尝试使用 Haskell 对变量进行舍入。

r :: Double -> Double
r x = round (x)

试图编译这个,我得到以下错误

没有因使用“round”而产生 (Integral Double) 的实例

我该如何解决这个问题?谢谢!

【问题讨论】:

    标签: haskell double rounding integral


    【解决方案1】:

    这是合乎逻辑的,因为作为Integral 实例的类型,嗯...,通常是“整数”。因此,这意味着它的行为类似于IntegerIntegral 的示例有 IntegerIntWord8 等。如错误所述,FloatDouble 等不是整数。

    您可以使用fromIntegral :; (Num b, Integral a) => a -> bIntegral 类型的内容转换为Numerical 类型:

    r :: Double -> Double
    r = fromIntegral . round

    例如:

    Prelude> r 14.25
    14.0
    

    【讨论】:

    • 不,这不起作用。 Double 是一个 frac,所以我不必使用 fromIntegral 将它声明为一个,对吗?但是,它不起作用。我遇到了和以前一样的错误。
    • @longroad:那么为什么前奏会以示例输出进行演示。 Double 是许多类型类的实例:EnumNumEqFloating 等。因此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)) | ^^^^^^^^^^^^^^^^^^^^^^^
    • @longroad:但是你把两者互换了,是fromIntegral (round x),注意我们在result上调用fromIntegral
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-09
    相关资源
    最近更新 更多