rubik
rubik

Reputation: 9104

Haskell, type mismatch between floor, toRational, and logBase

This is really bugging me. I want to find the largest m such that 2^m < n. This is what I did:

m = floor $ toRational $ logBase 2 n

GHCI complains:

No instance for (Floating Int) arising from a use of ‘logBase’
In the second argument of ‘($)’, namely ‘logBase 2 n’
In the second argument of ‘($)’, namely ‘toRational $ logBase 2 n’
In the expression: floor $ toRational $ logBase 2 n

I don't understand why, since:

*Main> :t logBase 
logBase :: Floating a => a -> a -> a
*Main> :t toRational 
toRational :: Real a => a -> Rational
*Main> :t floor 
floor :: (RealFrac a, Integral b) => a -> b

logBase returns a Floating, while toRational accepts a Real: this must work, since how can a Floating not be a Real. Then toRational returns a Rational, while floor accepts a RealFrac. I don't know what that is (I tried looking it up with :info RealFrac with little useful output), but how can a Rational not be a RealFrac?

The error has it with Floating Int, can you shed light on this for me? As a second question, how can I get more info about weird types like RealFrac inside GHCI? As I said :info RealFrac wasn't very helpful to me.

Upvotes: 1

Views: 114

Answers (1)

Lee
Lee

Reputation: 144126

It looks like n is type Int which has no instance for Floating. You can use fromIntegral:

m = floor $ toRational $ logBase 2 (fromIntegral n)

Upvotes: 4

Related Questions