为什么我们不能通过类型扩展来满足F#静态成员约束? [英] Why can't we satisfy F# static member constraints with type extensions?

查看:71
本文介绍了为什么我们不能通过类型扩展来满足F#静态成员约束?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望能够使用静态方法从其他库扩展类型以启用通用算术.例如,以微软公司新创建的SIMD友好的固定大小VectorN类型为例.他们定义了Zero,他们定义了(+),他们定义了(/),但是我不能在它们上使用Array.average,因为他们没有定义DivideByInt,我很乐意:

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. 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:

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)

但是抱怨不会让我编译

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

为什么在F#编译器中存在此限制?

Why does this limitation exist in the F# compiler?

(以前曾被问过.)

推荐答案

当前无法在类型扩展中定义运算符重载.有一个

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#中的全局运算符重载

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#静态成员约束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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