Haskell如何将整数文字转换为不同的类型? [英] How does Haskell convert integer literals to different types?

查看:111
本文介绍了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}

第二个例子,编译器如何转换 56 总和56

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

在前奏中,我看到 Sum 是一个 Num ,但不清楚转换。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆