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.

#light

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

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  
  member
x.Vacant = (x.numberOfRooms = 0)
  member
x.Filled = (x.numberOfRooms > x.CAPACITY)
 
member this.NumberOfRooms
  
with get() = this.numberOfRooms
  
and set((v:int)) = (this.numberOfRooms <- v) 
  new
() = { CAPACITY = 400
                 numberOfRooms = 0 }
 
end

open System
let motel1 = new motel()
Console.WriteLine(
"***** {0} *******", motel1.name)
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 )
Console.ReadLine()

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

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

COMMENT USING

PREMIUM SPONSORS

Hire Mobile & Web Developer on demand. 100% satisfaction. Try for 1 week or Money Back. Local and remote developers available all over USA.

Latest Blogs