Doing OO in F# : Defining an F# Class

By Mike Gold Jun 08, 2008
Although very much a functional language, F# provides us with object-oriented mechanisms such as classes, inheritance, and encapsulation. The sample below illustrates all three

Here we see three object-oriented mechanisms in action inside of F#.  hotel and motel are classes, class motel inherits class hotel, and the numberOfRooms is a privately encapsulated field of the motel class.  Also note that we publicly expose numberOfRooms with the property NumberOfRooms.


type hotel = class
val name : string
new() = {name = "Hotel California"}

type motel = class
inherit hotel
val mutable private numberOfRooms: int
val CAPACITY : int
member x.CalculateRate = (float)x.numberOfRooms * 125.50
  member x.IncrementRooms(n) = x.numberOfRooms <- x.numberOfRooms + n  
x.Vacant = (x.numberOfRooms = 0)
x.Filled = (x.numberOfRooms > x.CAPACITY)
member this.NumberOfRooms
with get() = this.numberOfRooms
and set((v:int)) = (this.numberOfRooms <- v) 
() = { CAPACITY = 400
                 numberOfRooms = 0 }

open System
let motel1 = new motel()
"***** {0} *******",
Console.WriteLine (
"number of rooms = {0}", motel1.NumberOfRooms)
if (motel1.Vacant) then
Console.WriteLine ("The motel is empty")
motel1.IncrementRooms (5)
Console.WriteLine (
"number of rooms = {0} costing {1:c}", motel1.NumberOfRooms, motel1 .CalculateRate )

if (motel1.Vacant) then
Console.WriteLine ("The hotel is empty")motel1.NumberOfRooms <- 400
Console.WriteLine (
"number of rooms = {0} costing {1:c}", motel1.NumberOfRooms, motel1.CalculateRate )

The code above excercises the IncrementRoom method and the NumberOfRooms Property to simulate the occupation of a motel.  It also calculates the total rate from the number of rooms occupied at any given time.

The result of running the code listed above is shown in the screenshot below.

Mike Gold
Mike Gold

Michael Gold is President of Microgold Software Inc., makers of the WithClass UML Tool. His company is a Microsoft VBA Partner and Borland Partner. Mike is a Microsoft MVP and founding member of C# Corner. He has a BSEE ... Read more