开发者

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

type Foo(...) =
    ...

let a = Array.开发者_运维技巧create 10 (new Foo())

let sum = Array.sum a


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜