# realToFrac vs. fromRealFrac

Marcin 'Qrczak' Kowalczyk qrczak@knm.org.pl
3 Feb 2001 13:14:12 GMT

```Sat, 03 Feb 2001 23:34:37 +1100, Manuel M. T. Chakravarty <chak@cse.unsw.edu.au> pisze:

>   fromIntegral :: (Integral a, Num b) => a -> b
>   fromRealFrac :: (RealFrac a, Fractional b) => a -> b
>
> (`fromRealFrac' is also defined in Figure 7.)
>
> However, in Appendix A ``Standard Prelude'', we have
>
>   realToFrac     :: (Real a, Fractional b) => a -> b
>   realToFrac      = fromRational . toRational
>
> instead of a definition for `fromRealFrac'.
>
> Both GHC and Hugs go by Appendix A.  What was the original
> intention?

I don't know. I always assumed that it's realToFrac. It yields a
quite consistent picture.

Classes provide conversions to and from two "universal" types:
toInteger  (from Integral), fromInteger  (to Num),
toRational (from Real),     fromRational (to Fractional).

There are also conversions with both ends overloaded, defined as
compositions of appropriate conversions going through an universal
type. One of them converts from Real to Fractional and is thus called
realToFrac. The other converts from Integral to Num, and since Num
in the context of numeric types does not mean anything (all numeric
types are Num), it is omitted from the name fromIntegral.

Classes for these four conversions are chosen in a natural way.
toInteger and toRational require that appropriate types contains
*at most* integral and real values. fromInteger and fromRational
require that the given type contains *at least* integral and fractional
values (and all numeric types contain at least integral values).

It follows that for most injections (except between one complex type
to another) either of fromIntegral or realToFrac works. If both work,
they give the same result, although fromIntegral should be slightly
more efficient. Narrowing the range or precision is not considered
a failure to be an injection.

fromRealFrac taking RealFrac as an argument does not make much sense:
it is not necessary to have fractional numbers to be convertible to
Rational, because integral types will do too.

--
__("<  Marcin Kowalczyk * qrczak@knm.org.pl http://qrczak.ids.net.pl/
\__/
^^                      SYGNATURA ZASTĘPCZA
QRCZAK

```