[Haskell-beginners] Addition of "Float" and "Int".

Sylvain Henry hsyl20 at gmail.com
Wed May 14 00:02:38 UTC 2014


>Is it that since both the formal args are defined as "a" they have to be
exactly the same instances?

Exactly.

>Had "+" been defined something like: (+) :: (Num a, Num b) => a -> b -> a
> my second addition would have worked?

Yes except that you cannot write this function given the definition of Num
http://hackage.haskell.org/package/base-4.7.0.0/docs/Prelude.html#t:Num

If you want your second example to work, you have to explicitly convert the
floating-point value into an Int (using floor, ceiling or round for
instance).

-Sylvain


2014-05-12 17:44 GMT+02:00 Venu Chakravorty <c.venu at aol.com>:

>   Hello everyone,
>  I am just starting with Haskell so please bear with me.
>
>  Here's my question:
>
>  Consider the below definition / output:
>
>  Prelude> :t (+)
> (+) :: (Num a) => a -> a -> a
>
>  What I understand from the above is that "+" is a function that takes
> two args
> which are types of anything that IS-AN instance of "Num" (Int, Integer,
> Float, Double)
> and returns an instance of "Num".
> Hence this works fine:
> Prelude> 4.3 + 2
> 6.3
>
>  But I can't understand why this doesn't work:
> Prelude> 4.3 + 4 :: Int
>
>  <interactive>:1:0:
>     No instance for (Fractional Int)
>       arising from the literal `4.3' at <interactive>:1:0-2
>     Possible fix: add an instance declaration for (Fractional Int)
>     In the first argument of `(+)', namely `4.3'
>     In the expression: 4.3 + 4 :: Int
>     In the definition of `it': it = 4.3 + 4 :: Int
>
>  I expected that the second addition would work as both "Float" and "Int"
> are
> instances of "Num". Is it that since both the formal args are defined as
> "a" they
> have to be exactly the same instances? Had "+" been defined something
> like:
> (+) :: (Num a, Num b) => a -> b -> a
> my second addition would have worked?
>
>  Please let me know what I am missing.
>
>  Regards,
> Venu Chakravorty.
>
> _______________________________________________
> Beginners mailing list
> Beginners at haskell.org
> http://www.haskell.org/mailman/listinfo/beginners
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://www.haskell.org/pipermail/beginners/attachments/20140514/f14df198/attachment.html>


More information about the Beginners mailing list