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?
The best I could come up with was
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)))
which still doesn't work (at least in FSI - haven't tried compiling). I'm not sure this is possible at all.
Instead, I suggest you use the IEnumerable<_>
extension methods in System.Linq
:
open System.Linq
[| 1..10 |].Sum()