2011-05-04 76 views
2

这是一个非常愚蠢的问题,但我有点失落。这里的功能在整数类型之间转换

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) 

我要补充,使其工作的错误?

回答

7

(**)是浮点求幂。您可能需要使用(^)

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类型类的实例,因此,你不能直接用就可以了(**) 。您可以转换为某种浮点类型并返回,但这里最好直接使用整数版本。另请注意,(^)只需要指数就是不可或缺的。该基地可以是任何数字类型。

相关问题