F#显式类型参数的用例是什么? [英] what is use cases of F# explicit type parameters?

查看:82
本文介绍了F#显式类型参数的用例是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道,值定义中的显式类型参数是克服值限制"问题的一种方法.
还有其他需要使用的情况吗?

As I know, explicit type parameters in value definitions is a one way to overcome "value restriction" problem.
Is there another cases when I need to use them?

更新:我的意思是显式通用构造",其中类型参数括在尖括号中,即

Upd: I mean "explicitly generic constructs", where type parameter is enclosed in angle brackets, i.e.

let f<'T> x = x

推荐答案

这可能很少见,但是当您要防止进一步泛化时(§14.6.7):

This would likely be rare, but when you want to prevent further generalization (§14.6.7):

关于值和成员定义的显式类型参数定义会影响类型推断和泛化的过程.特别是,包含显式泛型参数的声明将不会被泛化到那些泛型参数之外.例如,考虑以下功能:

Explicit type parameter definitions on value and member definitions can affect the process of type inference and generalization. In particular, a declaration that includes explicit generic parameters will not be generalized beyond those generic parameters. For example, consider this function:

let f<'T> (x : 'T) y = x

在类型推断期间,这将导致以下类型的函数,其中'_b是尚未解析的类型推断变量.

During type inference, this will result in a function of the following type, where '_b is a type inference variable that is yet to be resolved.

f<'T> : 'T -> '_b -> '_b

要允许在这些定义中进行泛化,请删除显式的泛型参数(如果可以推断出它们),或者使用所需数量的参数,如以下示例所示:

To permit generalization at these definitions, either remove the explicit generic parameters (if they can be inferred), or use the required number of parameters, as the following example shows:

let throw<'T,'U> (x:'T) (y:'U) = x

当然,您也可以使用类型注释来完成此操作.

Of course, you could also accomplish this with type annotations.

这篇关于F#显式类型参数的用例是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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