Haskell 函数的类型错误';地板';在哈斯克尔

Haskell 函数的类型错误';地板';在哈斯克尔,haskell,floating-point,int,Haskell,Floating Point,Int,我有一个函数接受2个整数n,x,并计算楼层(logn/logx)。这里n和x都非常有限,所以Int对我来说就足够了 func::Int->Int->Int func n x=楼层(对数from积分n/(对数from积分x)) 但ghci的错误来了: No instance for (RealFrac (a -> b)) arising from a use of `floor' at p5_evenly_divide.hs:20:11-63 Possible fix: add an

我有一个函数接受2个整数n,x,并计算楼层(logn/logx)。这里n和x都非常有限,所以Int对我来说就足够了


func::Int->Int->Int
func n x=楼层(对数from积分n/(对数from积分x))

但ghci的错误来了:

No instance for (RealFrac (a -> b))
  arising from a use of `floor' at p5_evenly_divide.hs:20:11-63
Possible fix: add an instance declaration for (RealFrac (a -> b))
In the expression:
    floor (log . fromIntegral n / (log . fromIntegral x))
In the definition of `func':
    func n x = floor (log . fromIntegral n / (log . fromIntegral x))

我怎样才能度过这个难关?

表达式
log。fromIntegral n
相当于
log。(from integral n)
,而不是
(log.from integral)n
,这可能是您想要的。不过,
log(fromn)
可能更具可读性

对于一般的启发,当错误消息说
No instance For(RealFrac(a->b))
时,它告诉您它无法理解如何将函数用作小数,因为您正在将函数组合
(..
应用于
from integral n
的结果。在这种情况下有点迟钝。

试试这个:

func :: Int -> Int -> Int 
func n x = floor (k n / k x) where
  k = log . fromIntegral

我喜欢你解释问题和解决问题的方法。这真的很有帮助。我认为错误信息是“floor”应该在RealFrac上使用,所以我一直在错误的方向上处理。@Ralph Zhang:这也是事实--
floor
(/)
需要一个小数类型,
fromIntegral
可以生成任何数字类型,唯一强制特定类型的是
(.)
。如果函数确实有一个
RealFrac
实例,那么一切都会进行类型检查,所以这就是它抱怨的地方。@camccann:+1用于很好的解释,+1用于信息注释,了解了(.)的一些新内容。
log$fromIntegral n
也非常可读,而且非常地道,afaict。