F# 扩展约束数组
F# extending constrained array
假设我有以下片段
type 'T``[]`` when 'T : (static member (+) : 'T -> 'T -> 'T) with
member inline self.sum = Array.fold ( + ) self
很显然,我只想在支持 +
运算符时添加扩展方法。
但是,我不断收到以下错误:
Error FS0957 One or more of the declared type parameters for this type extension have a missing or wrong type constraint not matching the original type constraints on '[]<_>'
这种具体的扩展方法是否可行?如果是,我错过了什么?
我能想到的最好的是
type 'T``[]`` with
member inline this.mysum< ^T when ^T : (static member (+) : ^T * ^T -> ^T)>() =
Array.reduce (fun v1 v2 -> (^T : (static member (+): ^T * ^T -> ^T) (v1, v2)))
这仍然不起作用(至少在 FSI 中——还没有尝试编译)。我不确定这是否可行。
相反,我建议您使用 System.Linq
中的 IEnumerable<_>
扩展方法:
open System.Linq
[| 1..10 |].Sum()
假设我有以下片段
type 'T``[]`` when 'T : (static member (+) : 'T -> 'T -> 'T) with
member inline self.sum = Array.fold ( + ) self
很显然,我只想在支持 +
运算符时添加扩展方法。
但是,我不断收到以下错误:
Error FS0957 One or more of the declared type parameters for this type extension have a missing or wrong type constraint not matching the original type constraints on '[]<_>'
这种具体的扩展方法是否可行?如果是,我错过了什么?
我能想到的最好的是
type 'T``[]`` with
member inline this.mysum< ^T when ^T : (static member (+) : ^T * ^T -> ^T)>() =
Array.reduce (fun v1 v2 -> (^T : (static member (+): ^T * ^T -> ^T) (v1, v2)))
这仍然不起作用(至少在 FSI 中——还没有尝试编译)。我不确定这是否可行。
相反,我建议您使用 System.Linq
中的 IEnumerable<_>
扩展方法:
open System.Linq
[| 1..10 |].Sum()