f# - 如何约束一个类型参数

标签 f#

有没有办法约束一个类型参数从另一个类型参数派生?

type Foo<'T, 'U when 'U :> 'T> = 
    member x.Bar() : 'T = upcast Unchecked.defaultof<'U>
此代码产生以下错误:

Error 1 Invalid constraint: the type used for the constraint is sealed, which means the constraint could only be satisfied by at most one solution

Error 2 This type parameter has been used in a way that constrains it to always be ''T'

Error 3 The static coercion from type 'T to 'T0 involves an indeterminate type based on information prior to this program point. Static coercions are not allowed on some types. Further type annotations are needed.

Warning 4 This construct causes code to be less generic than indicated by the type annotations. The type variable 'U has been constrained to be type ''T'.

最佳答案

否:(。(根据我的看法,这是目前F#最不幸的限制之一。请参阅规范的Solving Subtype Constraints部分,其中指出:

New constraints of the form type :> 'b are solved again as type = 'b.



这真的很可惜,因为否则我们可以解决F#缺少通用方差的问题:
let cvt<'a,'b when 'a :> 'b> (s:seq<'a>) : seq<'b> = // doesn't compile
  s |> box |> unbox

关于f# - 如何约束一个类型参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3857474/

相关文章:

java - 时间反向传播

f# - 从 FSharp 中的函数返回函数时无法理解类型推断

F# '+' 运算符重载和 List.fold

f# - 与 OCaml 的 'lsr' 和 'asr' 等效的 F# 按位运算符是什么?

list - 列表中最后一个元素的值

generics - F# 泛型并不那么通用

winforms - 在 F# 中绘制 Windows 窗体

f# - 如何在 F# 中枚举受歧视的联合?

f# - F#语法问题

具有多态(在 OO 意义上)返回类型的 F# 函数