Philippe
Philippe

Reputation: 670

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.

Upvotes: 3

Views: 2619

Answers (1)

Bergi
Bergi

Reputation: 664936

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)

Upvotes: 7

Related Questions