How to write a new type compatible with Array.sum?

type Foo(...) =
    ...

let a = Array.create 10 (new Foo())

let sum = Array.sum a
+5
source share
2 answers

You need to add several elements that are used by the function sumto calculate:

type Foo(value:int) = 
  member x.Value = value
  // Two members that are needed by 'Array.sum'
  static member (+) (a:Foo, b:Foo) = Foo(a.Value + b.Value)
  static member Zero = Foo(0)
  // Not needed for 'Array.sum', but allows 'Array.average'
  static member DivideByInt(a:Foo, n:int) = Foo(a.Value / n)

The function sumstarts with the value returned Zero, and then adds the values Foousing the overloaded operator +( averageand then divides the result by an integer):

let a = Array.init 10 (fun n -> Foo(n)) 
let sum = Array.sum a 
sum.Value // Returns 45
+10
source

Impossible.

If you want to use any Array method (sum, etc.), you must use an array type to store data.

: . , , +, - .. , .

-1

All Articles