简体   繁体   中英

No instance for (RealFrac Int) arising from a use of ' … '

The following program is supposed to check whether the input n is divisible by the sum of digits in n

module Harshad where

isHarshad :: Int -> Bool
isHarshad n = (mod n (sumDig n)) == 0)
 where 
  sumDig n 
   | (floor (n / 10) == 0) = n -- n consists of only one digit
   | otherwise = sumDig (floor (n / 10)) + floor (10*(n - floor (n / 10)))

I get the following compile error : * No instance for (RealFrac Int) arising from a use of `sumDig'

even after trying to add various conversions I'm still stuck.

Drop the fractionals altogether and use only div for integer division:

sumDig n = if n < 10 then n -- n consists of only one digit
           else sumDig (n `div` 10) + (n `mod` 10)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM