[Haskell-cafe] Proposal: Rational read

Michael Orlitzky michael at orlitzky.com
Mon Aug 15 15:09:52 UTC 2016


On 08/15/2016 09:04 AM, Benno Fünfstück wrote:
> 
> Well, you are showing 1/3 as a Float and reading it as a Double, which
> of course won't work since the String represents a Float and not a
> Double. The following does work:
> 

Sorry, unclear example. We have a choice to make for how to read in
decimal strings that could also represent Floats or Doubles. I'm worried
about the resulting confusion from whatever choice we make.

Read/Show are supposed to be machine-readable, and representing a
Rational as a decimal (the same way a Float is represented) gives away
some type-safety. This is the same argument I would make against having
(read "1.0" :: Integer) return 1.

Suppose that this is what the rational read instance would do...

  ghci> let ratread :: String -> Rational;
        ratread s = realToFrac (read s :: Double) :: Rational

We're compatible with the Fractional/Show instance for Float/Double:

  ghci> fromRational $ ratread (show (0.33333334 :: Float)) :: Float
  0.33333334
  ghci> fromRational $ ratread (show (0.33333334 :: Double)) :: Double
  0.33333334

But obviously things will go wrong for rationals themselves, when they
don't fit into a Double. The other choice we could make is to take
"0.33333334", multiply it by ten-to-the-whatever, and then make that the
denominator (over ten-to-the-whatever). That's probably a better choice,
but then you have other inconsistencies...

  ghci> 0.33333334 :: Rational
  16666667 % 50000000
  ghci> toRational (0.33333334 :: Float)
  11184811 % 33554432

Namely, that that's not how the Float itself is converted into a
Rational. Basically, beware of confusing the hell out of everyone in
order to avoid an explicit type conversion.



More information about the Haskell-Cafe mailing list