Haskell找到完美的正方形 - 获取类型错误

时间:2011-12-23 01:49:12

标签: haskell types casting functional-programming

我刚刚开始学习haskell,我试图实现一个简单的函数来检查数字是否是平方根。我认为我在理解Haskell类型系统时遇到了一些问题 - 我唯一的其他编程经验是ruby和一些Java。这是我到目前为止所做的(对不起,如果它真的很愚蠢):

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.

你能解释一下问题是什么,如何解决,最好是我不理解的任何基本概念?提前谢谢。

1 个答案:

答案 0 :(得分:5)

sqrt的类型为:

sqrt :: Floating a => a -> a

truncate的类型为:

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

换句话说,sqrt返回一个浮点数,而truncate返回一个整数。您必须插入显式转换。在这种情况下,您可能需要fromIntegral,它可以将任何整数类型转换为任何数字类型:

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

然后您可以进行比较:

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