[Haskell-cafe] Mixed-type arithmetic, or type coercion
Albert Y. C. Lai
trebla at vex.net
Tue Mar 13 17:12:02 EDT 2007
Dave Hinton wrote:
> Arithmetic operators in haskell appear to require their operands to
> have the same type. How can I do arithmetic between operands of
> different types?
>
> Alternatively, how do I coerce a value from being an Int to being a Double?
fromIntegral can do this coercion. It is more general: the input can be
Int or Integer; the output can be any numeric type.
There is also realToFrac: the input can be Int, Integer, Float, Double,
or Ratio a (eg Rational); the output can be Float, Double, Ratio a (eg
Rational), or Complex a.
(Someone please compare their costs wherever comparable. I have a
feeling that most compilers make fromIntegral faster than realToFrac
for, say, Int -> Double.)
When you have time, you may like to find out more about "type classes".
In short, it is the way Haskell provides operator overloading. Numeric
types use this scheme to achieve the above generality. If you know type
classes, you have access to the full story.
More information about the Haskell-Cafe
mailing list