Operator Overloading

F# allows overloading of common operators to create custom types. Below is the classic example of a complex type with operators for negation, addition and subtraction.

type complex(r:float, i:float) =
  member this.r = r
  member this.i = i

  static member(~-) (x:complex) =
  complex(-x.r, -x.i)

  static member(+) (x:complex, y:complex) =
  complex(x.r+y.r, x.i+y.i)

  static member(-) (x:complex, y:complex) =
  complex(x.r-y.r, x.i-y.i)

  static member(*) (x:complex, y:complex) =
  complex(x.r*y.r-x.i*y.i, x.r*y.i+x.i*y.r)

  override this.ToString () =
    if this.i >= 0.0 then
      sprintf "%g+%gi" this.r this.i
    else
      sprintf "%g%gi" this.r this.i

let a = complex(1.0, 2.0)
let b = complex(3.0, 4.0)
printfn "a=%O" a
printfn "b=%O" b
printfn "-a=%O" -a
printfn "a+b=%O" (a+b)
printfn "a-b=%O" (a-b)
printfn "a*b=%O" (a*b)

As you may recognize, printf does automatically invoke the ‘ToString’ method to print out complex numbers in a custom format when using the ‘%O’ parameter.

Advertisements
This entry was posted in Language. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s