[英]Haskell, type mismatch between floor, toRational, and logBase
這真是困擾我。 我想找到最大的m,使2 ^ m <n。 這是我所做的:
m = floor $ toRational $ logBase 2 n
GHCI抱怨:
No instance for (Floating Int) arising from a use of ‘logBase’
In the second argument of ‘($)’, namely ‘logBase 2 n’
In the second argument of ‘($)’, namely ‘toRational $ logBase 2 n’
In the expression: floor $ toRational $ logBase 2 n
我不明白為什么,因為:
*Main> :t logBase
logBase :: Floating a => a -> a -> a
*Main> :t toRational
toRational :: Real a => a -> Rational
*Main> :t floor
floor :: (RealFrac a, Integral b) => a -> b
logBase
返回一個Floating
,而toRational
接受一個Real
:這必須起作用,因為Floating
不能成為Real
。 然后toRational
返回一個Rational
,而floor
接受一個RealFrac
。 我不知道那是什么(我嘗試用:info RealFrac
進行:info RealFrac
,但幾乎沒有有用的輸出),但是Rational
不能成為RealFrac
嗎?
Floating Int
有錯誤,您可以幫我了解一下嗎? 第二個問題,我如何獲得RealFrac
諸如RealFrac
類的怪異類型的更多信息? 正如我所說的:info RealFrac
對我不是很有幫助。
看起來n
是Int
類型,沒有Floating
實例。 您可以使用fromIntegral
:
m = floor $ toRational $ logBase 2 (fromIntegral n)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.