gpt4 book ai didi

haskell - 如何使用Haskell吸顶函数

转载 作者:行者123 更新时间:2023-12-02 10:56:47 24 4
gpt4 key购买 nike

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

效果很好。

最佳答案

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

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 <b>(fromIntegral y)</b>) + 100

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

关于haskell - 如何使用Haskell吸顶函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53065105/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com