Mixed-type arithmetic, or type coercion

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? I am new to haskell. I have read a few tutorials but they do not mention this issue. I have read the haddock documentation for Prelude and Numeric, but cannot find anything that helps here. (I saw a couple of numeric conversion functions, but they won't turn an Int into a Double.) Toy example: $ cat eg.hs calc :: Int -> Double -> Double calc count weight = count * weight $ ghc eg.hs eg.hs:2: Couldn't match `Int' against `Double' Expected type: Int Inferred type: Double In the second argument of `(*)', namely `weight' In the definition of `calc': calc count weight = count * weight

Hi
Arithmetic operators in haskell appear to require their operands to have the same type. How can I do arithmetic between operands of different types?
You probably don't want to.
Alternatively, how do I coerce a value from being an Int to being a Double?
You ask Hoogle: http://haskell.org/hoogle/?q=Integer+-%3E+Double The answer is fromInteger/toInteger as required.
calc :: Int -> Double -> Double calc count weight = fromInteger (toInteger count) * weight
toInteger promotes the Int to an Integer, fromInteger then converts that to a Double. Thanks Neil

On Tue, 13 Mar 2007 21:41:00 +0100, Dave Hinton
how do I coerce a value from being an Int to being a Double?
calc :: Int -> Double -> Double calc count weight = count * weight
Use: calc count weight = fromIntegral count * weight If you want an Int result, use: calc count weight = count * round weight -- Met vriendelijke groet, Henk-Jan van Tuyl -- http://Van.Tuyl.eu/ -- Using Opera's revolutionary e-mail client: https://secure.bmtmicro.com/opera/buy-opera.html?AID=789433

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.
participants (4)
-
Albert Y. C. Lai
-
Dave Hinton
-
Henk-Jan van Tuyl
-
Neil Mitchell