Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Integer to Num conversion in Haskell

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

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.

>Solution :

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading