2011-12-23 111 views
2

我刚开始学习haskell,并试图实现一个简单的函数来检查数字是否是平方根。我想我有一些理解Haskell类型系统的问题 - 我唯一的其他编程经验是ruby和一些Java。这是我迄今(很抱歉,如果它真的傻):Haskell找到完美的方块 - 获取类型错误

isPerfectSquare :: (RealFloat t) => t -> Bool 
isPerfectSquare n = 
    (sqrt n) == (truncate (sqrt n)) 

这就是我会做的红宝石......但在这里它给了我这个错误:

Could not deduce (Integral t) arising from a use of `truncate' 
from the context (RealFloat t) 
    bound by the type signature for 
      isPerfectSquare :: RealFloat t => t -> Bool 
    at more.hs:(73,1)-(74,35) 
Possible fix: 
    add (Integral t) to the context of 
    the type signature for isPerfectSquare :: RealFloat t => t -> Bool 
In the second argument of `(==)', namely `(truncate (sqrt n))' 
In the expression: (sqrt n) == (truncate (sqrt n)) 
In an equation for `isPerfectSquare': 
    isPerfectSquare n = (sqrt n) == (truncate (sqrt n)) 
Failed, modules loaded: none. 

莫非你请解释什么是问题,如何解决问题,最好是我不了解的基本概念?提前致谢。

回答

5

SQRT具有类型:

sqrt :: Floating a => a -> a 

截断具有类型:

truncate :: (RealFrac a, Integral b) => a -> b 

换句话说,SQRT返回一个浮点数,而截断返回一个整数。你必须插入一个明确的转换。在这种情况下,你可能想fromIntegral,它可以在任何整数类型转换为任何数值类型:

fromIntegral :: (Num b, Integral a) => a -> b 

然后,您可以作出比较:

(sqrt n) == (fromIntegral $ truncate (sqrt n)) 
+0

感谢,这正是我一直在寻找!我想我只需要学习很多东西。 – V9801 2011-12-23 02:19:04