F# 显式成员约束:类型变量 ^T 无法泛化,因为它会超出其作用域 [英] F# explicit member constraints: The type variable ^T could not be generalized because it would escape its scope

查看:16
本文介绍了F# 显式成员约束:类型变量 ^T 无法泛化,因为它会超出其作用域的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 F# 中使用显式成员约束.文档说F# 支持公共语言运行时支持的完整约束集",但是如果我实际编译一个具有这样显式约束的类,如下所示,我会得到相当奇怪的错误.

I'm attempting to use explicit member constraints in F#. The documentation says "F# supports the complete set of constraints that is supported by the common language runtime", but if I actually compile a class with such an explicit constraint, such as the following, I get quite the exotic error.

type MyType<'T when ^T: (static member ( + ) : ^T * ^T -> ^T)> =
    member this.F a b = a + b

报告

错误 FS0670:此代码不够通用.类型变量 ^T 当 ^T : (静态成员 ( + ) : ^T * ^T -> ^T) 不能泛化,因为它会超出其范围.

error FS0670: This code is not sufficiently generic. The type variable ^T when ^T : (static member ( + ) : ^T * ^T -> ^T) could not be generalized because it would escape its scope.

并在定义成员this.F的站点上报.这是什么意思?相关范围是什么?

And reports it at the site of defining member this.F. What does this mean? What is the relevant scope?

该语言支持多种方法来完成此类工作.可以在此处在 StackOverflow 上找到一个不错的探索,但我还没有看到明确的解释为什么不允许这个特定的通用约束转义".

There are a number of approaches supported by the language for doing this sort of work. A nice exploration can be found here on StackOverflow, but I've not seen a clear explanation of why this particular generic constraint is not allowed to 'escape'.

推荐答案

F# 规范:

^ident 形式的类型是静态解析的变量类型.一个新类型推断变量是创建并添加到类型推理环境(参见第 14.6 节).这个类型变量被标记为表明它可能不是的属性除内联外的一般化定义(见第 14.7 节),同样任何类型变量通过类型推断方程等同可能同样不能推广.

A type of the form ^ident is a statically resolved variable type. A fresh type inference variable is created and added to the type inference environment (see §14.6). This type variable is tagged with an attribute indicating it may not be generalized except at inline definitions (see §14.7), and likewise any type variable with which it is equated via a type inference equation may similarly not be generalized.

http://research.microsoft.com/en-us/um/cambridge/projects/fsharp/manual/spec.html

这篇关于F# 显式成员约束:类型变量 ^T 无法泛化,因为它会超出其作用域的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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