是否可以将 DivideByInt 添加到现有类型?
Is it possible to add DivideByInt to existing types?
给定 TimeSpan
个值的列表,我想得到平均值 TimeSpan
。如果能这样写就好了:
let durations = [TimeSpan.FromSeconds 4.; TimeSpan.FromSeconds 2.]
let avg = durations |> List.average
然而,编译器对此有抱怨:
The type 'TimeSpan' does not support the operator 'DivideByInt'
这很合理,因为 TimeSpan
确实没有定义 DivideByInt。
为了解决这个问题,我尝试像这样扩展 TimeSpan
(在使用 List.average
之前):
type TimeSpan with
static member DivideByInt (ts : TimeSpan) (i : int) =
(float ts.Ticks) / (float i) |> int64 |> TimeSpan.FromTicks
虽然此实现在直接使用时似乎可以正常工作,但不幸的是,在使用 List.average
.
时似乎并不能让编译器满意
虽然我非常清楚我可以使用 List.averageBy,或者只是编写一个自定义函数来计算 TimeSpan
值列表的平均值,但我认为它会很优雅如果可以写 durations |> List.average
.
有什么方法可以启用该语法吗?
当我尝试使用
重载操作时
type TimeSpan with
member this.op_DivideByInt (ts : TimeSpan) (i : int) =
(float ts.Ticks) / (float i) |> int64 |> TimeSpan.FromTicks
let durations = [TimeSpan.FromSeconds 4.; TimeSpan.FromSeconds 2.]
let avg = durations |> List.average
我收到以下编译器警告:
Extension members cannot provide operator overloads. Consider defining the operator as part of the type definition instead.
看来我们不能这样做了。
不,这不可能。看到这个 old question。理论上可能会在 F# 的未来版本中实现它。
给定 TimeSpan
个值的列表,我想得到平均值 TimeSpan
。如果能这样写就好了:
let durations = [TimeSpan.FromSeconds 4.; TimeSpan.FromSeconds 2.]
let avg = durations |> List.average
然而,编译器对此有抱怨:
The type 'TimeSpan' does not support the operator 'DivideByInt'
这很合理,因为 TimeSpan
确实没有定义 DivideByInt。
为了解决这个问题,我尝试像这样扩展 TimeSpan
(在使用 List.average
之前):
type TimeSpan with
static member DivideByInt (ts : TimeSpan) (i : int) =
(float ts.Ticks) / (float i) |> int64 |> TimeSpan.FromTicks
虽然此实现在直接使用时似乎可以正常工作,但不幸的是,在使用 List.average
.
虽然我非常清楚我可以使用 List.averageBy,或者只是编写一个自定义函数来计算 TimeSpan
值列表的平均值,但我认为它会很优雅如果可以写 durations |> List.average
.
有什么方法可以启用该语法吗?
当我尝试使用
重载操作时type TimeSpan with
member this.op_DivideByInt (ts : TimeSpan) (i : int) =
(float ts.Ticks) / (float i) |> int64 |> TimeSpan.FromTicks
let durations = [TimeSpan.FromSeconds 4.; TimeSpan.FromSeconds 2.]
let avg = durations |> List.average
我收到以下编译器警告:
Extension members cannot provide operator overloads. Consider defining the operator as part of the type definition instead.
看来我们不能这样做了。
不,这不可能。看到这个 old question。理论上可能会在 F# 的未来版本中实现它。