5
type Foo(...) =
    ...

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

let sum = Array.sum a

2 Answers 2

10

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
2
  • Thanks! BTW, how about implementing member Cos on a type, so that it works with Core.Operators.cos too?
    – elmattic
    Jul 19, 2010 at 12:41
  • @Stringer: Supporting cos is possible too (the member declaration would be static member Cos(a:Foo) = a - note that it has to return value of type Foo as the result). There are quite a few standard library functions that can be supported using members... Jul 19, 2010 at 14:21
-1

Not possible.

When you want to use any method of Array (sum, etc), you must use an array type for the data storage.

EDIT: I misinterpreted your question. You might want to try to implement certain operator overloads such as +, - etc. Maybe the type would then support the sum method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.