[Haskell-cafe] multi type addition

aditya siram aditya.siram at gmail.com
Tue Dec 28 23:46:36 CET 2010


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.html#t:Real
[2] http://hackage.haskell.org/packages/archive/base/latest/doc/html/Prelude.html#t:Rational

On Tue, Dec 28, 2010 at 3:45 PM, william murphy <will.t.murphy at gmail.com> wrote:
> 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 at haskell.org
> http://www.haskell.org/mailman/listinfo/haskell-cafe
>
>



More information about the Haskell-Cafe mailing list