首页 > 解决方案 > F# extending constrained array

问题描述

Say I have the following snippet

type 'T``[]`` when 'T : (static member (+) : 'T -> 'T -> 'T) with
    member inline self.sum = Array.fold ( + ) self

It's hopefully obvious that I want to add an extension method only when 'T supports the + operator.

However, I keep getting the following errors:

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 '[]<_>'

Is this specific of an extension method possible? If it is, what am I missing?

标签: genericsf#extension-methodsgeneric-programming

解决方案


我能想到的最好的办法是

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 中 - 没有尝试编译)。我不确定这是否可能。

相反,我建议您使用以下IEnumerable<_>扩展方法System.Linq

open System.Linq
[| 1..10 |].Sum()

推荐阅读