Monday, February 18, 2008

Two ways of defining classes in F#

While reading documentation about F# I learned about two ways for defining classes.

In F# you have several options for defining data structures including records, discriminated unions and classes . A nice resource for learning about the syntax of class definitions is Object Model Syntax Examples also F# Overview (III.) - Imperative and Object-Oriented Programming and the F# Manual: Class definitions provide more information.

The first way of defining classes defines the object construction parts explicitly:

type Shape = class
val x : int
val y : int

new(aX,aY) =
{ x = aX ;
y = aY }

override self.ToString() =
string.Format("({0},{1})",self.x, self.y)


type Square = class
inherit Shape as baseClass
val side : int

new (aX,aY,aSide) = {
inherit Shape(aX,aY) ;
side = aSide

override self.ToString() =
string.Format("{0} -- {1}",baseClass.ToString(), self.side)

The second way uses implicit construction:

type Shape(x : int,y : int) = class
override self.ToString() =
string.Format("({0},{1})",x, y)


type Square(x : int,y : int,side : int) = class
inherit Shape(x,y) as baseClass

override self.ToString() =
string.Format("{0} -- {1}",baseClass.ToString(), side)


No comments: