【问题标题】:Converting between integer types整数类型之间的转换
【发布时间】:2011-08-18 07:57:09
【问题描述】:

这是一个非常愚蠢的问题,但我有点迷路了。这是函数

f :: (Bool,Int) -> Int
f (True,n) = round (2 ** n)
f (False,n) = 0

这是我遇到的一个错误

No instance for (Floating Int)
  arising from a use of `**'
Possible fix: add an instance declaration for (Floating Int)
In the first argument of `round', namely `(2 ** n)'
In the expression: round (2 ** n)
In an equation for `f': f (True, n) = round (2 ** n)

我应该添加什么才能使其正常工作?

【问题讨论】:

    标签: haskell floating-point int typeclass


    【解决方案1】:

    (**) 是浮点取幂。您可能想改用(^)

    f :: (Bool,Int) -> Int
    f (True,n)  = 2^n
    f (False,n) = 0
    

    查看类型很有帮助:

    Prelude> :t (**)
    (**) :: Floating a => a -> a -> a
    Prelude> :t (^)
    (^) :: (Num a, Integral b) => a -> b -> a
    

    错误消息告诉您Int 不是Floating 类型类的实例,因此您不能直接在其上使用(**)。您可以转换为一些浮点类型并返回,但这里最好直接使用整数版本。另请注意,(^) 只要求 exponent 是整数。基数可以是任何数字类型。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-16
      • 1970-01-01
      • 2021-08-12
      • 2019-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多