1

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 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.

1
  • In Haskell there are no implicit conversions: an Integer is not automatically promoted to, say, Double -- we need to call fromInteger to explicitly convert the value. The only exception are numeric literals: 123 is automatically converted to the numeric type the context requires, essentially behaving as if the use wrote fromInteger (123::Integer). All the other expressions (including variables) are not subject to this automatic conversion. Commented Nov 12, 2021 at 9:51

1 Answer 1

4

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.