我正在尝试编写函数来检查参数是否为整数的平方:
isSquare :: Int -> Bool
isSquare x = truncate(sqrt(x)) * truncate(sqrt(x)) == x当我加载函数时,我得到了错误:
Prelude> :load "some.hs"
[1 of 1] Compiling Main ( some.hs, interpreted )
some.hs:2:13:
No instance for (RealFrac Int)
arising from a use of `truncate' at some.hs:2:13-29
Possible fix: add an instance declaration for (RealFrac Int)
In the first argument of `(*)', namely `truncate (sqrt (x))'
In the first argument of `(==)', namely
`truncate (sqrt (x)) * truncate (sqrt (x))'
In the expression: truncate (sqrt (x)) * truncate (sqrt (x)) == x
some.hs:2:22:
No instance for (Floating Int)
arising from a use of `sqrt' at some.hs:2:22-28
Possible fix: add an instance declaration for (Floating Int)
In the first argument of `truncate', namely `(sqrt (x))'
In the first argument of `(*)', namely `truncate (sqrt (x))'
In the first argument of `(==)', namely
`truncate (sqrt (x)) * truncate (sqrt (x))'
Failed, modules loaded: none.但是如果我尝试执行:
Prelude> truncate(sqrt(9))*truncate(sqrt(9))==9
True一切都很好。
为什么我得到这个错误,以及如何修复它?
发布于 2010-12-02 17:36:16
你把整数当做浮点数。因此,类型不匹配。
使用fromIntegral
isSquare :: Int -> Bool
isSquare n = truncate(sqrt(x)) * truncate(sqrt(x)) == n
where x = fromIntegral n发布于 2010-12-03 02:46:56
不是所有的效率,但一个可爱的方法来判断一个数字是否是一个平方,只使用整数算术:
isSquare x = x == head (dropWhile (< x) squares)
where squares = scanl1 (+) [1,3..]https://stackoverflow.com/questions/4333459
复制相似问题