How to use Haskell ceiling function

Viewed 2446
test_1 :: Int -> Int
test_1 y = 5 * 10 ^ (ceiling ( logBase 10 y  ) )  + 100

Here is the error message:

parse.hs:23:22: error:
    • No instance for (RealFrac Int) arising from a use of ‘ceiling’
    • In the second argument of ‘(^)’, namely
        ‘(ceiling (logBase 10 y))’
      In the second argument of ‘(*)’, namely
        ‘10 ^ (ceiling (logBase 10 y))’
      In the first argument of ‘(+)’, namely
        ‘5 * 10 ^ (ceiling (logBase 10 y))’

parse.hs:23:32: error:
    • No instance for (Floating Int) arising from a use of ‘logBase’
    • In the first argument of ‘ceiling’, namely ‘(logBase 10 y)’
      In the second argument of ‘(^)’, namely ‘(ceiling (logBase 10 y))’
      In the second argument of ‘(*)’, namely
        ‘10 ^ (ceiling (logBase 10 y))’
Failed, modules loaded: none.

But if I try this function by simply using a real number:

test = 5 * 10 ^ (ceiling ( logBase 10 1000 ) )  + 100

It works fine.

1 Answers

But if I try this function by simply using a real number:

test = 5 * 10 ^ (ceiling ( logBase 10 1000 ) )  + 100

Here 1000 is not interpreted as an Int, but as a Floating type. This is necessary, since the type of logBase has type logBase :: Floating a => a -> a -> a.

You can convert an Integral type like an Int to a Num type with fromIntegral :: (Integral a, Num b) => a -> b:

test_1 :: Int -> Int
test_1 y = 5 * 10 ^ ceiling (logBase 10 (fromIntegral y)) + 100

But perhaps it makes more sense to perform the log10 in integer space instead.

Related