[Haskell-cafe] about integer and float operations
Yitzchak Gale
gale at sefer.org
Wed Feb 4 14:07:13 EST 2009
Manlio Perillo wrote:
> The first difference is about a `mod` b, when a and b are Float types.
> Python use the fmod function, and it also implement divmod; Haskell seems to
> lack support for this operation.
Yes, Haskell does not implement the full IEEE. There are
differing opinions about that: some say we should add it all
in, and some say we should take it all out. Floating point
is ugly, but useful.
It seems that enough of IEEE is implemented for the vast
majority of applications, so far.
> The second difference is about the division of two integers.
>>>> 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
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
In Haskell, the various integral and floating point types are
completely separate. The literal 777 is overloaded - its type is
777 :: Num a => a
so it can be used for both integral and floating point types.
But the division operators are separate:
div :: Integral a => a -> a -> a
(/) :: Fractional a => a -> a -> a
So when you use 777 together with /, the 777 is interpreted
as a Fractional (defaulting to Double). And when you use
it with div, the 777 is interpreted as an Integral (defaulting
to Integer).
Hope this helps,
Yitz
More information about the Haskell-Cafe
mailing list