dan*_*tel 8 haskell types typeclass ghc
我正在学习Haskell.我创建了函数,它将乘法表返回到'b'中的'n'.数字填充为'w'数字.作为最后一步,我想自动计算'w'.为什么这不编译?
-- Number of digits needed for the multiplication table n*n in base 'base'
nOfDg :: Int -> Int-> Int
nOfDg n base = 1 + floor ( logBase base (n*n))
Run Code Online (Sandbox Code Playgroud)
错误:
No instance for (Floating Int)
arising from a use of `logBase' at C:\haskel\dgnum.hs:4:24-38
Possible fix: add an instance declaration for (Floating Int)
In the first argument of `floor', namely `(logBase b (n * n))'
In the second argument of `(+)', namely `floor (logBase b (n * n))'
In the expression: 1 + floor (logBase b (n * n))
Run Code Online (Sandbox Code Playgroud)
max*_*ori 11
logBase采用两个实现浮动类型类的参数.在将参数传递给logBase之前,您需要在参数上调用fromIntegral.这是为6.10.3编译的:
nOfDg :: Int -> Int-> Int
nOfDg n base = 1 + floor ( logBase (fromIntegral base) (fromIntegral (n*n)))
Run Code Online (Sandbox Code Playgroud)
你必须记住,Haskell是非常强类型的,所以你不能只假设提供给你的函数的Int参数将被自动强制转换为日志函数通常采用的浮点数.
logBase声明适用于浮点类型.Int不是浮点类型,Haskell中没有自动转换.试试这个:
-- Number of digits needed for the multiplication table n*n in base 'base'
nOfDg :: Int -> Float -> Int
nOfDg n base = 1 + floor (logBase base (fromIntegral (n*n)))
Run Code Online (Sandbox Code Playgroud)