Willie Ekaputra
Willie Ekaputra

Reputation: 45

Haskell type Converting errors

a newbie and have made this code in winHugs Haskell to check the maximum exponent k can be induced, that 2 power k is the divisor of n:

maxexp2 ::Int -> Int
maxexp2 n 
    | n==0 || 2^k`mod`n /= 0  = 0
    | otherwise == k
  where k = e `div` f    
        e = round (fromIntegral(log n))
        f = round (fromIntegral (log 2))

Somehow I know there is something fishy with the e and f part ...the error says : fractional Int instance is needed for the execution of this function. I don't really understand that...can someone please explain it to me ?

Upvotes: 0

Views: 103

Answers (1)

leftaroundabout
leftaroundabout

Reputation: 120711

Obviously, the logarithm of almost all numbers is something irrational, so using fromIntegral on it should indeed seem fishy to you. Why do you even think you need it on that point? Where you do need it is before the logarithm, because that actually also accepts only values of the Floating class, as we can easily find out1:

Prelude> :t log
log :: Floating a => a -> a

So it hase to be e = round (log $ fromIntegral n). You don't need it for f at all, because 2 is just a generic Num literal, not an Int. Obviously though, it can't be right to just round the log 2, because that is simply 1. What you probably want is round $ e / f with floating-point e and f.


1I don't know if this works in Hugs; probably. If not, use GHCi (why does everybody new seem to use Hugs at the moment anyway? I don't know why you would use anything else but GHC).

Upvotes: 1

Related Questions