Home > OS >  Integer to Num conversion in Haskell
Integer to Num conversion in Haskell

Time:11-12

I was just playing around with Haskell typeclasses and I discovered an error that I am not able to understand.

Here is the code that reproduces it:

fun :: (Num a) => Integer -> a
fun a = a   1

Error:

Couldn't match expected type ‘a’ with actual typeInteger

Now, as I understand it, Integer is an instance of the Num Typeclass and Integer type meets all the requirements defined by Num. Is this kind of conversion not allowed? Isn't this the point of using creating a Typeclass, i.e. 'a' is any instance of typeclass Num.

CodePudding user response:

The ( ) :: Num a => a -> a -> a means that the two operands and the result all have the same type. This thus means that for an expression a 1 since a is an Integer, it means that 1 and a 1 are Integers as well.

Your function however promises that for any type a where Num a holds, it can construct a function that maps an Integer to an object of that type a. So that can be an Integer, Int, Double, etc.

You can make use of the fromInteger :: Num a => Integer -> a function to convert the result to any Num type with:

fun :: Num a => Integer -> a
fun = fromInteger (a   1)
  • Related