没有 (Floating Int) 的实例 [英] No instance for (Floating Int)

查看:22
本文介绍了没有 (Floating Int) 的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 Haskell.我创建了一个函数,它在基数b"中将乘法表返回到n".数字被填充到w"数字.作为最后一步,我想自动计算 'w'.为什么这不能编译?

I am learning Haskell. I have created function which returns multiplication table up to 'n' in base 'b'. Numbers are padded to 'w' digits. As the last step, I want to compute 'w' automatically. Why does this not compile?

-- 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)) 

错误:

No instance for (Floating Int)
     arising from a use of `logBase' at C:haskeldgnum.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))

推荐答案

logBase 有两个实现浮动类型类的参数.在将参数传递给 logBase 之前,您需要对参数调用 fromIntegral.这是用 6.10.3 为我编译的:

logBase takes two parameters which implement the floating typeclass. You'll need to call fromIntegral on the parameters before passing them to logBase. This compiled for me with 6.10.3:

nOfDg :: Int -> Int-> Int
nOfDg n base = 1 + floor ( logBase (fromIntegral base) (fromIntegral (n*n)))

您必须记住,Haskell 是强类型的,因此您不能假设提供给函数的 Int 参数会自动强制转换为日志函数通常采用的浮点数.

You have to remember that Haskell is very strongly typed, so you can't just assume that the Int parameters supplied to your function will automatically be coerced to the floating numbers that log functions generally take.

这篇关于没有 (Floating Int) 的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆