gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 17:41:16 27 4
gpt4 key购买 nike

type Foo(...) =
...

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

let sum = Array.sum a

最佳答案

您需要添加一些 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)
sum函数从 Zero 返回的值开始然后添加 Foo 的值使用重载 +运算符( average 然后将结果除以一个整数):
let a = Array.init 10 (fun n -> Foo(n)) 
let sum = Array.sum a
sum.Value // Returns 45

关于f# - 如何编写与 Array.sum 兼容的新类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3280231/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com