如何使用 Haskell 天花板函数

una*_*der 4 haskell

test_1 :: Int -> Int
test_1 y = 5 * 10 ^ (ceiling ( logBase 10 y  ) )  + 100
Run Code Online (Sandbox Code Playgroud)

这是错误消息:

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.
Run Code Online (Sandbox Code Playgroud)

但是如果我简单地使用一个实数来尝试这个函数:

test = 5 * 10 ^ (ceiling ( logBase 10 1000 ) )  + 100
Run Code Online (Sandbox Code Playgroud)

它工作正常。

Wil*_*sem 5

但是如果我简单地使用一个实数来尝试这个函数:

test = 5 * 10 ^ (ceiling ( logBase 10 1000 ) )  + 100
Run Code Online (Sandbox Code Playgroud)

这里1000不是解释为Int,但作为一个Floating类型。这是必要的,因为类型logBase具有 type logBase :: Floating a => a -> a -> a

您可以转换的Integral类型像IntNum类型有fromIntegral :: (Integral a, Num b) => a -> b

test_1 :: Int -> Int
test_1 y = 5 * 10 ^ ceiling (logBase 10 (fromIntegral y)) + 100
Run Code Online (Sandbox Code Playgroud)

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