代码之家  ›  专栏  ›  技术社区  ›  elmattic

如何编写与Array.sum兼容的新类型?

f#
  •  5
  • elmattic  · 技术社区  · 14 年前
    type Foo(...) =
        ...
    
    let a = Array.create 10 (new Foo())
    
    let sum = Array.sum a
    
    2 回复  |  直到 14 年前
        1
  •  10
  •   Tomas Petricek    14 年前

    sum

    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)
    

    这个 函数以返回的值开始 Zero 然后添加 Foo 使用过载 + 操作员( average

    let a = Array.init 10 (fun n -> Foo(n)) 
    let sum = Array.sum a 
    sum.Value // Returns 45
    
        2
  •  -1
  •   Laurens Ruijtenberg    14 年前

    不可能。

    当您想使用任何数组方法(sum等)时,您必须为数据存储使用数组类型。