截断的问题::(RealFrac a,Integral b)=> a - > b

时间:2011-10-12 11:48:18

标签: haskell

我正在使用滞后素数除数,我对这段代码感到麻烦:

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

错误消息是:

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.

我的打字似乎缺乏。我该怎么做才能使这段代码有效?

1 个答案:

答案 0 :(得分:9)

sqrt n替换为sqrt $ fromIntegral n

问题是sqrt的类型为(Floating a) => a -> a,因此它不适用于整数。功能

fromIntegral :: (Integral a, Num b) => a -> b

从整数类型“强制转换”为更一般的Num个实例。