Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

f#

type Foo(...) =
    ...

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

let sum = Array.sum a
like image 349
Stringer Avatar asked Jul 19 '10 10:07

Stringer


1 Answers

You need to add a few members that are used by the sum function to do the calculation:

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 sum function starts with the value returned by Zero and then adds values of Foo using the overloaded + operator (average 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
like image 74
Tomas Petricek Avatar answered Sep 20 '22 22:09

Tomas Petricek