Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Haskell convert integer literals to different types?

Tags:

haskell

I have following anonymous function:

*Exercises> g = \(Sum n) -> Sum (n - 1)

I use it like:

*Exercises> g (Sum 56)
Sum {getSum = 55}
*Exercises> g 56
Sum {getSum = 55}

The second example, how does the compiler convert 56 to Sum 56?

In the prelude, I saw that Sum is an instance of Num, but it not clear about the conversion.

like image 443
softshipper Avatar asked Jun 28 '17 12:06

softshipper


1 Answers

When Haskell sees an integer literal such as 56, it interprets it as fromInteger 56. The type of fromInteger is Num a => Integer -> a, so the type of this code is Num a => a. (Any type, here called a, which is a member of the Num class.)

This means that when you use it in a context where a member of Num is expected (Sum in your case), it will "set" a to Sum, and pick the version of fromInteger of type Integer -> Sum. Thus fromInteger 56 :: Sum.

like image 158
Dan Avatar answered Sep 28 '22 18:09

Dan