F# 模块扩展与类型扩展
如果我想为浮点数组定义一个扩展方法,例如标准差,那么使用数组模块上的模块扩展或 float[]
类型上的扩展会更好吗? 就像:
module Array =
let std (arr: float[]) = ...
或者
type float ``[]`` with
member this.std = ...
如果我像后者那样输入扩展,那么 std 是否只计算一次或每次使用时计算?
而且,后者的正确格式是什么,显然 type float ``[]`` with
不兼容...谢谢。
if I want to define a extension method for float array like standard deviation, would it be better to use module extension on Array module or extension on type float[]
?
like :
module Array =
let std (arr: float[]) = ...
or
type float ``[]`` with
member this.std = ...
If I do type extension as the latter, would the std
be only calculated once or every time it is used?
And, what is the right format for the latter, apprently type float ``[]`` with
does not comile... thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在这种情况下,您无法定义类型扩展,因此问题没有实际意义 - 您必须使用 Array 模块的扩展。无法定义类型扩展的原因是,在 F# 中,类型扩展必须完全镜像类型定义,因此您可以在通用
'a list
类型上定义类型扩展,但是不在构造类型字符串列表
上。同样,您可以在(模拟的)泛型数组类型上定义扩展方法,但不能在构造的数组类型上
定义扩展方法。此行为与 C# 不同,在 C# 中可以在构造的泛型类型上编写扩展方法。
In this case, you can't define a type extension so the issue is moot - you must use an extension of the
Array
module. The reason that you can't define a type extension is that in F#, type extensions must exactly mirror type definitions, so you can define a type extension on the generic'a list
type, for instance, but not on the constructed typestring list
. Similarly, you could define an extension method on the (simulated) generic array typebut not on the constructed array type
This behavior is different than C#, where it is possible to write extension methods on constructed generic types.