Kevin Meredith
Kevin Meredith

Reputation: 41919

Function Composition with RealFrac and Floating Int

I'm trying to compose 3 functions.

ghci> let f = floor . (logBase 2) . length

However, I don't understand this compile-time error.

<interactive>:47:9:
    No instance for (RealFrac Int) arising from a use of `floor'
    Possible fix: add an instance declaration for (RealFrac Int)
    In the first argument of `(.)', namely `floor'
    In the expression: floor . (logBase 2) . length
    In an equation for `f': f = floor . (logBase 2) . length

<interactive>:47:18:
    No instance for (Floating Int) arising from a use of `logBase'
    Possible fix: add an instance declaration for (Floating Int)
    In the first argument of `(.)', namely `(logBase 2)'
    In the second argument of `(.)', namely `(logBase 2) . length'
    In the expression: floor . (logBase 2) . length

In this output:

    No instance for (RealFrac Int) arising from a use of `floor'
    Possible fix: add an instance declaration for (RealFrac Int)

Does that mean I need to explicitly specify the type (via :: some_type_here) rather than rely on Haskell to infer the type?

Upvotes: 0

Views: 98

Answers (1)

Sibi
Sibi

Reputation: 48746

That's because the type of logbase is:

λ> :t logbase
logBase :: Floating a => a -> a -> a

So, they accept type which are instances of Floating typeclass ie. Float and Double data type. So if you do proper type conversion, it should work:

λ> let f = floor . (logBase 2) . fromIntegral . length

Upvotes: 4

Related Questions