在整数类型之间转换

syn*_*pse 2 floating-point int haskell typeclass

这是一个非常愚蠢的问题,但我有点失落.这是功能

f :: (Bool,Int) -> Int
f (True,n) = round (2 ** n)
f (False,n) = 0
Run Code Online (Sandbox Code Playgroud)

这是我得到的错误

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)
Run Code Online (Sandbox Code Playgroud)

我应该添加什么才能使它工作?

ham*_*mar 7

(**)是浮点指数.您可能想要使用(^).

f :: (Bool,Int) -> Int
f (True,n)  = 2^n
f (False,n) = 0
Run Code Online (Sandbox Code Playgroud)

查看类型很有帮助:

Prelude> :t (**)
(**) :: Floating a => a -> a -> a
Prelude> :t (^)
(^) :: (Num a, Integral b) => a -> b -> a
Run Code Online (Sandbox Code Playgroud)

错误消息告诉您这Int不是Floating类型类的实例,因此您无法(**)直接使用它.您可以转换为某种浮点类型并返回,但在这里最好直接使用整数版本.另请注意,(^)只需要指数为整数.基数可以是任何数字类型.