[Haskell-cafe] ANN: convertible (first release)

Bertram Felgenhauer bertram.felgenhauer at googlemail.com
Wed Jan 28 12:05:10 EST 2009

wren ng thornton wrote:
> John Goerzen wrote:
>> Hi folks,
>> I have uploaded a new package to Haskell: convertible.  At its heart,
>> it's a very simple typeclass that's designed to enable a reasonable
>> default conversion between two different types without having to
>> remember a bunch of functions.
> I once again point out that realToFrac is *wrong* for converting from Float 
> or Double.

Yes, realToFrac is just broken, or at least the Real instances of Float
and Double are. Of course, with the restriction to single parameter type
classes in Haskell98, it's hard to come up with anything better - we'd
end up with fooToBar for all Real / Fractional pairs.

>     > realToFrac (1/0::Float) ::Double
>     3.402823669209385e38
>     >
>     > realToFrac (0/0::Float) ::Double
>     -5.104235503814077e38
>     > realToFrac (0/0::Double) ::Float
>     -Infinity


GHC makes the mess just a bit messier. The following program prints
different answers when compiled with -O or without:

    main = do
        print (realToFrac (1/0::Float) :: Double)
        print (realToFrac (0/0::Float) :: Double)
        print (realToFrac (0/0::Double) :: Float)

Without -O:

With -O:

The reason for this behaviour are rules replacing realToFrac by direct
conversions from Float to Double or vice versa, where applicable. These
two evils -- realToFrac and changing the behaviour with -O -- amount to
something good: proper treatment of NaNs and Infinities.

Your RealToFrac class is a definitive improvement over this situation.


More information about the Haskell-Cafe mailing list