
We were trying to make an addition function that, unlike the library one, could add numbers of different types from the typeclass 'Num.' We originally ran into a problem when trying to add (5 :: Integer) + 4.8, and were trying to define a new function that would be able to get that: (+') :: (Num a, Num b) => a -> b -> Float x +' b = d + e where d :: Float d = x e :: Float e = b This gave us the error: Couldn't match expected type `Float' against inferred type `b' `b' is a rigid type variable bound by the type signature for `pl' at test.hs:9:18 In the expression: b In the definition of `e': e = b In the definition of `pl': pl x b = d + e where d :: Float d = x e :: Float e = b Failed, modules loaded: none.

The problem here is that unfortunately the Haskell type system cannot do coercion. There is however a toRational method "Real" typeclass that converts instances of Num and Ord to Rational data type and a fromRational method that converts back. So your code could be: myplus :: (Real a, Real b) => a -> b -> Float a `myplus` b = fromRational(toRational a + toRational b)
(1 :: Integer) `myplus` (2::Integer) 3.0 (1.5 :: Float) `myplus` (2::Integer) 3.5
-deech
[1] http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.htm...
[2] http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.htm...
On Tue, Dec 28, 2010 at 3:45 PM, william murphy
We were trying to make an addition function that, unlike the library one, could add numbers of different types from the typeclass 'Num.' We originally ran into a problem when trying to add (5 :: Integer) + 4.8, and were trying to define a new function that would be able to get that:
(+') :: (Num a, Num b) => a -> b -> Float x +' b = d + e where d :: Float d = x e :: Float e = b
This gave us the error:
Couldn't match expected type `Float' against inferred type `b' `b' is a rigid type variable bound by the type signature for `pl' at test.hs:9:18 In the expression: b In the definition of `e': e = b In the definition of `pl': pl x b = d + e where d :: Float d = x e :: Float e = b Failed, modules loaded: none.
_______________________________________________ Haskell-Cafe mailing list Haskell-Cafe@haskell.org http://www.haskell.org/mailman/listinfo/haskell-cafe

On Tue, 28 Dec 2010, aditya siram wrote:
The problem here is that unfortunately the Haskell type system cannot do coercion.
I'd omit the "unfortunately". For me it is a good thing that Haskell does not silently apply lossy number conversions, as e.g. MatLab does. 'realToFrac' allows conversion to Float. It requires 'Real' constraint. Your 'Num' constraint is too weak, since 'Complex' is also in 'Num' type class. http://www.haskell.org/haskellwiki/Converting_numbers http://www.haskell.org/haskellwiki/Generic_number_type
participants (3)
-
aditya siram
-
Henning Thielemann
-
william murphy