Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does F# have generic arithmetic support?

Does F# have the same problem as C# where you can't directly use arithmetic operators with generic T types?

Can you write a generic Sum function that would return the sum of any value that supports the arithmetic addition?

like image 320
Joan Venge Avatar asked Feb 09 '10 00:02

Joan Venge


People also ask

What does f x → Y mean?

A function f from X to Y is an object that, for each element x ∈ X, assigns an element y ∈ Y . We use the notation f : X → Y to denote a function as described. We write f(x) = y or f : x ↦→ y to denote that the element in Y assigned to x is y. We call X the domain of f, and we call Y the codomain of f.

Does f mean derivative?

Derivative as a functionLet f be a function that has a derivative at every point in its domain. We can then define a function that maps every point x to the value of the derivative of f at x. This function is written f′ and is called the derivative function or the derivative of f.

What does f say about f and f?

f, f′ and f″ Since (f′)′=f″, when f′ is increasing, f″ is positive. Similarly, when the slopes of tangent lines are decreasing, i.e. when f′ is decreasing, the function is concave down, as you can see in the second two graphs below. Since (f′)′=f″, when f′ is decreasing, f″ is negative.


1 Answers

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.

like image 193
Tomas Petricek Avatar answered Oct 23 '22 10:10

Tomas Petricek