开发者

Type error of function 'floor' in Haskell

I have a function accepting 2 Ints n, x, and calculates floor (log n/log x). Here n and x are both very limited so Int is enough for me.

func :: Int -> Int -> Int

func n x = floor (log . fromIntegral n / (log . fromInt开发者_如何学JAVAegral x))

but here comes the error in 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))

How can I get through this?


The expression log . fromIntegral n is equivalent to log . (fromIntegral n), not (log . fromIntegral) n, which is probably what you wanted. Just log (fromIntegral n) is probably more readable, though.

For general edification, when the error message says No instance for (RealFrac (a -> b)) it's telling you it can't figure out how to use a function as a fractional number, which it's trying to do because you're applying function composition (.) to the result of fromIntegral n. It is a little obtuse in this case.


Try this:

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜