我刚刚开始学习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.
您能否解释一下问题是什么、如何解决它,以及最好是我不理解的任何基本概念?提前致谢。
最佳答案
sqrt 的类型为:
sqrt :: Floating a => a -> a
截断具有类型:
truncate :: (RealFrac a, Integral b) => a -> b
换句话说,sqrt 返回 float ,而 truncate 返回整数。您必须插入显式转换。在这种情况下,您可能需要 fromIntegral
,它可以将任何整数类型转换为任何数字类型:
fromIntegral :: (Num b, Integral a) => a -> b
然后您可以进行比较:
(sqrt n) == (fromIntegral $ truncate (sqrt n))
关于Haskell 求完美平方——出现类型错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8611476/