[Haskell-cafe] reading and writing Data.Ratio.Rational

Olaf Klinke olf at aatal-apotheke.de
Fri Feb 24 12:17:52 UTC 2017


Dear cafe, 

when processing text files containing numbers of the form "xxxx.yyyy" I used to parse them into Double using that type's Read instance. Obviously, even with arithmetic no more complicated than the field operations the result might have ugly rounding errors like 12.000000000002 due to the fact that numbers like 0.7 are not dyadic rationals. The math in my program is not complicated and the numbers are not large, so I don't care about Rationals having potentially huge memory footprints. 

So here's my question. A literal like 0.7 has type Fractional a => a, but the Read instance of Rational rejects the string "0.7". Must it be this way? Do I have to go via toRational.(read :: String -> Data.Scientific.Scientific)? 

Note that the documentation of Data.Scientific explicitly states that using (/) is unsafe, so I'd rather stay with the field Rational. 

For the output as decimal expansion, there is of course long division as described here [1], but I wonder whether either this exists in some library or there is even a more efficient solution.

Any pointers are appreciated.
Thanks,
Olaf

[1] http://stackoverflow.com/questions/30931369/how-to-convert-a-rational-into-a-pretty-string


More information about the Haskell-Cafe mailing list