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

fra*_*nza 1 haskell

我正在玩lagrest prime divisor,我遇到了这段代码的麻烦:

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
Run Code Online (Sandbox Code Playgroud)

错误消息是:

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.
Run Code Online (Sandbox Code Playgroud)

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

Fre*_*Foo 9

替换sqrt nsqrt $ fromIntegral n.

问题是sqrt有类型(Floating a) => a -> a,所以它不适用于整数.功能

fromIntegral :: (Integral a, Num b) => a -> b
Run Code Online (Sandbox Code Playgroud)

从整数类型到更一般的Num实例"强制转换" .