Search code examples
f#operator-overloadingoverloadingdiscriminated-union

Operator overloading / support discriminated unions in F#


I have a discriminated union (tagged value) which is supposed to represent the degree of a polynomial

type Degree =
    |MinusInf
    |Fin of int

So I have a function which gives me the degree of a polynomial

>deg [1;2;3;4];;
val it : Degree = Fin 3

Now, my question is, how can I make a function which allows me to add degrees so that:

 Fin 2 + Fin 3 = Fin 5

All best


Solution

  • There's a fairly detailed article on MSDN. In short, you want to define a function like this on your Degree type:

    type Degree =
        |MinusInf
        |Fin of int
        static member (+) (a: Degree, b: Degree) : Degree =
            match a, b with
            | Fin x, Fin y -> Fin (x+y)
            | _, _ -> MinusInf
    
    let x = Fin 2 + Fin 3