如何使用Haskell天花板功能

时间:2018-10-30 13:13:52

标签: haskell

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

这是错误消息:

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.

但是如果我仅使用实数来尝试此功能:

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

它工作正常。

1 个答案:

答案 0 :(得分:4)

  

但是如果我仅使用实数来尝试此功能:

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

此处1000不会解释为Int,而是解释为Floating类型。这是必需的,因为logBase的类型为logBase :: Floating a => a -> a -> a

您可以使用fromIntegral :: (Integral a, Num b) => a -> bIntegral这样的Int类型转换为Num类型:

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

但是也许改为在整数空间中执行log10更有意义。