简体   繁体   中英

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:

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, ie 'a' is any instance of typeclass Num.

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 Integer s 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM