RealFrac和Floating Int的函数组合

时间:2014-09-27 18:52:21

标签: haskell

我试图编写3个函数。

ghci> let f = floor . (logBase 2) . length

但是,我不理解这个编译时错误。

<interactive>:47:9:
    No instance for (RealFrac Int) arising from a use of `floor'
    Possible fix: add an instance declaration for (RealFrac Int)
    In the first argument of `(.)', namely `floor'
    In the expression: floor . (logBase 2) . length
    In an equation for `f': f = floor . (logBase 2) . length

<interactive>:47:18:
    No instance for (Floating Int) arising from a use of `logBase'
    Possible fix: add an instance declaration for (Floating Int)
    In the first argument of `(.)', namely `(logBase 2)'
    In the second argument of `(.)', namely `(logBase 2) . length'
    In the expression: floor . (logBase 2) . length

在此输出中:

    No instance for (RealFrac Int) arising from a use of `floor'
    Possible fix: add an instance declaration for (RealFrac Int)

这是否意味着我需要明确指定类型(通过:: some_type_here)而不是依靠Haskell来推断类型?

1 个答案:

答案 0 :(得分:4)

那是因为logbase的类型是:

λ> :t logbase
logBase :: Floating a => a -> a -> a

因此,他们接受的类型是Floating类型类的实例,即。 FloatDouble数据类型。因此,如果您进行了正确的类型转换,它应该可以工作:

λ> let f = floor . (logBase 2) . fromIntegral . length