Haskell中的floor
仅针对RealFrac
类型类定义。我对这个类型类了解不多,我的其余代码只使用浮点数。
我找不到任何将Float
转换为Int
的功能.如果有,那么floor
将等同于fromIntegral (fromFloating x)
,fract
将被定义为
fract x = x - floor x
但是,正如我所说,我还没有找到任何功能可以像我想fromFloating
做的事情一样。所以这是我能想到的实现fract
的唯一方法:
fract x
| x < 0 = 1 - fract (abs x)
| x < 1 = x
| otherwise = fract (x - 1)
然后当然floor x
会x - fract x
.然而,上面的算法是O(n(,它会大大减慢速度,所以我希望有一种方法可以做到这一点,那就是恒定的时间。
正如注释所说,floor
已经为浮点数实现了,frac
很简单; 这段代码编译:
aDouble :: Double
aDouble = -5.675
aFloat :: Float
aFloat = 10.675
frac :: RealFrac a => a -> a
frac x = x - fromIntegral (floor x :: Integer)
main :: IO ()
main = do
putStrLn "aDouble is"
print aDouble
putStrLn "frac(aDouble) is"
print (frac aDouble)
putStrLn "aFloat is"
print aFloat
putStrLn "frac(aFloat) is"
print (frac aFloat)
并产生:
$ runhaskell /tmp/a.hs
aDouble is
-5.675
frac(aDouble) is
0.3250000000000002
aFloat is
10.675
frac(aFloat) is
0.6750002