[Haskell-cafe] about integer and float operations

Yitzchak Gale gale at sefer.org
Wed Feb 4 16:44:19 EST 2009

Manlio Perillo wrote:
>>>>>> fac(777) / fac(777)
>>> 1.0
>>> Here CPython does not convert the two integers to float before to divide
>>> them, but make use of a special algorithm.
>>> GHC, instead, returns NaN

I wrote:
>> No, actually here Haskell shines. Perhaps this GHCi session
>> will illuminate the issue for you:
>> Prelude> let fac n = product [2..n]
>> Prelude> fac 777 `div` fac 777
>> 1
>> Prelude> fac 777 / fac 777
>> NaN

> No, this is not as complete as it is done in Python.
> The `/` operator *always* ...return a float...
> The `//` operator *always* perform a "floor" division.
> This happens for both integers and floats:
> If I'm correct, there is no operator/function, in Haskell, that perform an
> exact division between two integers and return a float:
> exactDiv :: (Integral a, Real b) => a -> a -> b

exactDiv :: (Real a, Real b, Fractional c) => a -> b -> c
x `exactDiv` y = realToFrac x / realToFrac y

Python does that same type coercion automatically at runtime.
This can sometimes make your code look a bit neater,
but other times really gets in the way.

> I personally prefer the Python solution, where we have two operators with
> the same behaviour over all the numbers.

If you really like exactDiv better, you can define an
operator to do it for you. But most people don't.

Haskell gives you total control, since the types of everything
are strictly defined at compile time. This has the extra
advantage of giving you a really powerful type checker
that can find many of your bugs at compile time.


More information about the Haskell-Cafe mailing list