简体   繁体   English

为什么我们不能满足带有类型扩展的F#静态成员约束?

[英]Why can't we satisfy F# static member constraints with type extensions?

I'd like to be able to extend types from other libraries with static methods to enable generic arithmetic. 我希望能够使用静态方法从其他库扩展类型以启用泛型算法。 Take, for example, the newly minted SIMD-friendly fixed-size VectorN types from Microsoft. 以微软新推出的SIMD友好型固定尺寸VectorN类型VectorN They define Zero , they define (+) , they define (/) , but I can't use Array.average on them because they don't define DivideByInt , which I'd be happy to: 它们定义Zero ,它们定义(+) ,它们定义(/) ,但我不能在它们上使用Array.average ,因为它们没有定义DivideByInt ,我很乐意:

open System.Numerics
type Vector2f with 
  static member DivideByInt (v:Vector2f) (i:int) = v / Vector2f(single i, single i)
let bigArray : Vector2f[] = readABigFile()
printf "the average is %A" (Array.average bigArray)

But it won't let me compile, complaining 但它不会让我编译,抱怨

error FS0001: The type 'Vector2f' does not support the operator 'DivideByInt'

Why does this limitation exist in the F# compiler? 为什么F#编译器中存在此限制?

(Edit: essentially the same question was asked previously .) (编辑:基本上问同样的问题。)

It is not currently possible to define an operator overload in a type extension. 目前无法在类型扩展中定义运算符重载。 There is an F# language user voice item for this (with quite a lot of votes) and so this is something that might change in future versions of F# (I think it would be great addition that fits nicely with the F# design). 有一个F#语言用户语音项目 (有相当多的投票),所以这可能会在未来的F#版本中发生变化(我认为这将是很好的补充,非常适合F#设计)。

If you absolutely need something like this today, you can either create a lightweight wrapper for your type that adds the operators, or you can use a (somewhat scary) trick that lets you hide the standard operator with a new overloaded one. 如果你今天绝对需要这样的东西,你可以为你的类型创建一个轻量级的包装器来添加操作符,或者你可以使用一个(有点可怕的)技巧,让你用一个新的重载方法隐藏标准操作符。 The following question has both examples: Global operator overloading in F# 以下问题有两个例子: F#中的全局运算符重载

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM