How does Haskell convert integer literals to different types?

馋奶兔 提交于 2020-01-03 12:31:05

问题


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.


回答1:


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.



来源:https://stackoverflow.com/questions/44802606/how-does-haskell-convert-integer-literals-to-different-types

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!