Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse a decimal fraction into Rational in Haskell?

I've been participating in a programming contest and one of the problems' input data included a fractional number in a decimal format: 0.75 is one example.

Parsing that into Double is trivial (I can use read for that), but the loss of precision is painful. One needs to be very careful with Double comparisons (I wasn't), which seems redundant since one has Rational data type in Haskell.

When trying to use that, I've discovered that to read a Rational one has to provide a string in the following format: numerator % denominator, which I, obviously, do not have.

So, the question is:

What is the easiest way to parse a decimal representation of a fraction into Rational?

The number of external dependencies should be taken into consideration too, since I can't install additional libraries into the online judge.

like image 362
Rotsor Avatar asked Aug 14 '11 12:08

Rotsor


People also ask

How do you change a rational number from a fraction to a decimal?

In order to change a rational number to a decimal, we divide the numerator with the denominator. In order to change a rational number to a decimal, we just convert the number into the form of a fraction. We then divide the numerator with the denominator and find out the exact value of the division.

What is fractional in Haskell?

Fractional is the class of types that can represent (exactly or at least in a decent approximation) any rational number. It may ad lib also be able to represent other numbers, but that's not important.


1 Answers

The function you want is Numeric.readFloat:

Numeric Data.Ratio> fst . head $ readFloat "0.75" :: Rational
3 % 4
like image 186
Yitz Avatar answered Sep 30 '22 13:09

Yitz