您想要的函数是 Numeric.readFloat
:
Numeric Data.Ratio> fst . head $ readFloat "0.75" :: Rational
3 % 4
以下是(GHCi 会话)的内容:
> :m + Data.Ratio
> approxRational (read "0.1" :: Double) 0.01
1 % 10
toRational
! - RotsorapproxRational 0.999 0.0001
得到的结果是 909 % 910
,这并不是我想要的。在这种情况下应该使用的正确 epsilon 是 0.000001
(精度的平方?) - Rotsorimport Data.Ratio ( (%) )
readRational :: String -> Rational
readRational input = read intPart % 1 + read fracPart % (10 ^ length fracPart)
where (intPart, fromDot) = span (/='.') input
fracPart = if null fromDot then "0" else tail fromDot
readSigned
:fst . head $ readSigned readFloat "-3.14" :: Rational
。 - newacct