[Haskell-cafe] Dividing integers?

Arjan van IJzendoorn afie at cs.uu.nl
Thu Mar 18 15:07:11 EST 2004

> I don't understand why I get this error. I mean, apparently "/" is not
defined for integers but I don't know
> how to "cast" the result of the length function into a Double...

Use div for dividing integers with loss of precision:
  3 `div` 2 (or: div 3 2)  == 1

"Casting" an Int to a Float/Double can be done using fromIntegral:

  fromIntegral (length [1,2]) / 3  == 0.6666666666666666

> Besides, a simple integer division works:

> Prelude> 2 / 3
> 0.6666666666666666

This is not an integer division. Writing down a literal (like 2 or 3)
denotes a number, not necessarily an Int. The context will influence what
type it will be. Something I find really confusing myself, too (which is why
it is not in Helium :-).

Greetings, Arjan

More information about the Haskell-Cafe mailing list