2

Given a list of TimeSpan values, I would like to get the average TimeSpan. It would be elegant if I could just write it like this:

let durations = [TimeSpan.FromSeconds 4.; TimeSpan.FromSeconds 2.]
let avg = durations |> List.average

However, the compiler complains about this:

The type 'TimeSpan' does not support the operator 'DivideByInt'

which is quite reasonable, since TimeSpan indeed doesn't define DivideByInt.

To work around this issue, I attempted to extend TimeSpan like this (before using List.average):

type TimeSpan with
    static member DivideByInt (ts : TimeSpan) (i : int) = 
        (float ts.Ticks) / (float i) |> int64 |> TimeSpan.FromTicks

While this implementation seems to work correctly when used directly, it unfortunately doesn't seem to make the compiler happy when using List.average.

While I'm very much aware that I can use List.averageBy, or just write a custom function to calculate the average of a list of TimeSpan values, I thought it'd be elegant if one could write durations |> List.average.

Is there any way to enable that syntax?

Nikos Baxevanis
  • 10,868
  • 2
  • 46
  • 80
Mark Seemann
  • 225,310
  • 48
  • 427
  • 736
  • Does TimeSpan have a static member Zero? https://msdn.microsoft.com/en-us/library/ee353446.aspx?f=255&MSPPError=-2147217396 – Ricardo Rodrigues Jun 02 '15 at 15:33
  • You could use a wrapper on which the static members `DivideByInt`, `(+)` and `Zero` are defined. Duplicate of this [question](http://stackoverflow.com/questions/20338670/project-new-values-from-existing-value)... – kaefer Jun 02 '15 at 16:21

2 Answers2

2

No, it's not possible. See this old question. In theory it might be possible to implement it in a future version of F#.

Community
  • 1
  • 1
Gus
  • 25,839
  • 2
  • 51
  • 76
0

when I tried to overload the op using

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

I get the following compiler warning: Extension members cannot provide operator overloads. Consider defining the operator as part of the type definition instead.

so it looks like we can't do this.

Chester Husk
  • 1,408
  • 12
  • 14