我试图编写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来推断类型?
答案 0 :(得分:4)
那是因为logbase
的类型是:
λ> :t logbase
logBase :: Floating a => a -> a -> a
因此,他们接受的类型是Floating
类型类的实例,即。 Float
和Double
数据类型。因此,如果您进行了正确的类型转换,它应该可以工作:
λ> let f = floor . (logBase 2) . fromIntegral . length