首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >truncate的麻烦::(RealFrac a,Integral b) => a -> b

truncate的麻烦::(RealFrac a,Integral b) => a -> b
EN

Stack Overflow用户
提问于 2011-10-12 19:48:18
回答 1查看 1.2K关注 0票数 2

我使用的是lagrest素除数,但我对下面的代码有问题:

代码语言:javascript
复制
lpd :: Integer -> Integer
lpd n = helper n (2:[3,5..ceiling])
  where
    helper n divisors@(d:ds)
      | n == d         = n
      | n `rem` d == 0 = helper (n `div` d) divisors
      | otherwise      = helper n ds
    ceiling = truncate $ sqrt n

错误消息为:

代码语言:javascript
复制
problems.hs:52:15:
    No instance for (RealFrac Integer)
      arising from a use of `truncate'
    Possible fix: add an instance declaration for (RealFrac Integer)
    In the expression: truncate
    In the expression: truncate $ sqrt n
    In an equation for `ceiling': ceiling = truncate $ sqrt n

problems.hs:52:26:
    No instance for (Floating Integer)
      arising from a use of `sqrt'
    Possible fix: add an instance declaration for (Floating Integer)
    In the second argument of `($)', namely `sqrt n'
    In the expression: truncate $ sqrt n
    In an equation for `ceiling': ceiling = truncate $ sqrt n
Failed, modules loaded: none.

我的打字好像不太好。我该怎么做才能让这段代码工作呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-10-12 19:51:14

sqrt $ fromIntegral n替换sqrt n

问题是sqrt的类型是(Floating a) => a -> a,所以它不能处理整数。函数

代码语言:javascript
复制
fromIntegral :: (Integral a, Num b) => a -> b

从整数类型到更通用的Num实例的“强制转换”。

票数 10
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7739598

复制
相关文章

相似问题

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