首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >是方格检查吗?

是方格检查吗?
EN

Stack Overflow用户
提问于 2010-12-02 17:30:08
回答 2查看 3.8K关注 0票数 4

我正在尝试编写函数来检查参数是否为整数的平方:

代码语言:javascript
复制
isSquare :: Int -> Bool
isSquare x = truncate(sqrt(x)) * truncate(sqrt(x)) == x

当我加载函数时,我得到了错误:

代码语言:javascript
复制
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.

但是如果我尝试执行:

代码语言:javascript
复制
Prelude> truncate(sqrt(9))*truncate(sqrt(9))==9
True

一切都很好。

为什么我得到这个错误,以及如何修复它?

EN

回答 2

Stack Overflow用户

发布于 2010-12-02 17:36:16

你把整数当做浮点数。因此,类型不匹配。

使用fromIntegral

代码语言:javascript
复制
isSquare :: Int -> Bool
isSquare n = truncate(sqrt(x)) * truncate(sqrt(x)) == n
             where x = fromIntegral n
票数 3
EN

Stack Overflow用户

发布于 2010-12-03 02:46:56

不是所有的效率,但一个可爱的方法来判断一个数字是否是一个平方,只使用整数算术:

代码语言:javascript
复制
isSquare x = x == head (dropWhile (< x) squares)
  where squares = scanl1 (+) [1,3..]
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4333459

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档