Haskell如何将整数文字转换为不同的类型? [英] How does Haskell convert integer literals to different types?
问题描述
我有以下匿名函数:
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}
第二个例子,编译器如何转换 56
至总和56
?
The second example, how does the compiler convert 56
to Sum 56
?
在前奏中,我看到 Sum
是一个 Num $的实例c $ c>,但不清楚转换。
In the prelude, I saw that Sum
is an instance of Num
, but it not clear about the conversion.
推荐答案
当Haskell看到一个整数字面值时,如 56
,它将它解释为来自整数56
。 fromInteger 的类型是
Num a =>整数 - > a
,所以这段代码的类型是 Num a =>一个
。 (任何类型,这里称为 a
,它是 Num
类的成员。)
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.)
这意味着当您在预期 Num
成员的上下文中使用它时( Sum
在你的情况下),它将设置 a
为 Sum
,并选择版本 fromInteger
类型 Integer - >总和
。因此来自整数56 :: Sum
。
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
.
这篇关于Haskell如何将整数文字转换为不同的类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!