1

I am writing an assembly with some functionality that is intended to work with numeric primitives, i.e. float, int, decimal, etc.

One of the functions takes two sequences and calculates the running average of the two. An implementation for floats may look like this

let average x y = (x+y)/2.
let a = [1..10] |> List.map float
let b = List.rev [1..10] |> List.map float
let result = (a, b) ||> List.map2 average

How can I make this generic for numeric primitives?

kasperhj
  • 10,052
  • 21
  • 63
  • 106

1 Answers1

3

F# has so called "static member constraints" that can be used for writing generic numerical code. This is limited to F# (because .NET has no concept like this).

In general, you need to mark the function as inline. This will make the standard operators inside the function behave as generic. In addition, you need to avoid using constants (like 2.0). You can typically replace them with some operation from the LanguagePrimitives module. For example, your average function can be written as generic using:

let inline average x y = 
  LanguagePrimitives.DivideByInt (x + y) 2

For more information check out this blog post about generic numeric computations in F#.

Tomas Petricek
  • 240,744
  • 19
  • 378
  • 553