Does F# have generic arithmetic support?

As brian mentioned, there is some built-in support for generic arithmethic and you can use ‘static constraints’ which allow you to define some generic functions yourself (although this is a bit limited).

In addition to this, you can also use dynamic ‘numeric associations’, which is a bit slower when using in a function, but it can be nicely used for example to define your own vector or matrix type. Here is an example:

#r "FSharp.PowerPack.dll"
open Microsoft.FSharp.Math

let twoTimesLarger (n:'a) (m:'a) = 
  let ops = GlobalAssociations.GetNumericAssociation<'a>()
  let sel = if ops.Compare(n, m) > 0 then n else m
  ops.Multiply(sel, ops.Add(ops.One, ops.One))

We first need to reference F# PowerPack library which contains the functionality. Then we define a generic function with a signature 'a -> 'a -> 'a. The first line dynamically gets numeric operations for working with the type 'a (it essentially uses some lookup table with the type as the key). Then you can use methods of the numeric operations object to perform things like multiplication, addition (Multiply, Add) and many others. The function works with any numbers:

twoTimesLarger 3 4  
twoTimesLarger 2.3 2.4
twoTimesLarger "a" "b" // Throws an exception!

When you define your own numeric type, you can define its numeric operations and register them using GlobalAssociations.RegisterNumericAssociation. I believe this also means that you’ll be able to use built-in F# Matrix<YourType> and Vector<YourType> after registering the operations.

Leave a Comment