我刚刚开始学习haskell,我试着实现一个简单的函数来检查一个数字是否是平方根。我想我在理解Haskell类型的系统时遇到了一些问题--我唯一的其他编程经验是ruby和一些Java。这就是我到目前为止所做的(如果真的很愚蠢,很抱歉):
isPerfectSquare :: (RealFloat t) => t -> Bool
isPerfectSquare n =
(sqrt n) == (truncate (sqrt n))这就是我在ruby中会做的..。但在这里,它给出了这个错误:
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.你能解释一下问题是什么吗,如何解决它,最好是我不理解的基本概念?提前谢谢。
发布于 2011-12-23 09:53:15
sqrt的类型为:
sqrt :: Floating a => a -> a截断具有以下类型:
truncate :: (RealFrac a, Integral b) => a -> b换句话说,sqrt返回一个浮点数,而truncate返回一个整数。您必须插入显式转换。在这种情况下,您可能需要fromIntegral,它可以将任何整数类型转换为任何数值类型:
fromIntegral :: (Num b, Integral a) => a -> b然后,您可以进行比较:
(sqrt n) == (fromIntegral $ truncate (sqrt n))https://stackoverflow.com/questions/8611476
复制相似问题