2011-10-12 54 views
1

我玩lagrest素因子和我有這個代碼的麻煩:故障與截斷::(RealFrac一,積分B)=>甲 - >乙

lpd :: Integer -> Integer 
lpd n = helper n (2:[3,5..ceiling]) 
    where 
    helper n [email protected](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. 

看來,我的打字缺乏。我能做些什麼來使這個代碼有效?

回答

9

sqrt n替換爲sqrt $ fromIntegral n

問題是sqrt的類型爲(Floating a) => a -> a,所以它不適用於整數。功能

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

「從整體類型轉換」到更一般的Num實例。