Home

Records & Enumerations

   

Description

Just like the primitive types, a member of a record can be created as an enumeration type. Of course, you must use an existing enumeration. You can one of the existing types such as those defined in the .NET Framework, or you can create your own enumeration. Here is an example:

type OccupancyStatus =
    | . . .
    
type Apartment = {
    UnitNumber      : string
    Bedrooms        : int
    Bathrooms       : float
    SecurityDeposit : int
    MonthlyRate     : int
    Status          : OccupancyStatus  }

When creating an object from the record, make sure you assign a member of the enumeration to the member of the record. You can then access the enumerated member outside the record. Here is an example:

open System
open System.Drawing
open System.Windows.Forms

type OccupancyStatus =
| Other       = 0
| Available   = 1
| Occupied    = 2
| NeedsRepair = 3

type Apartment = {
    UnitNumber      : string
    Bedrooms        : int
    Bathrooms       : float
    SecurityDeposit : int
    MonthlyRate     : int
    Status          : OccupancyStatus }

let apartmentRental : Form = new Form()
apartmentRental.Width <- 347
apartmentRental.Text <- "Lambda Square Apartments"
apartmentRental.Height <- 160

let lbxApartments = new ListBox()
lbxApartments.Left   <-  12
lbxApartments.Top    <-  12
lbxApartments.Width  <- 315
lbxApartments.Height <- 120
lbxApartments.Items.Add ("Unit #\tBeds\tBaths\tDeposit\tRate/month Status") |> ignore
lbxApartments.Items.Add ("--------------------------------------------------------------------------------------------") |> ignore
apartmentRental.Controls.Add lbxApartments

let showApartment(apart : Apartment) =
    lbxApartments.Items.Add (sprintf "%s\t%i\t%0.02f\t%i\t%i\t%A" apart.UnitNumber apart.Bedrooms apart.Bathrooms apart.SecurityDeposit apart.MonthlyRate apart.Status) |> ignore

let createApartment nbr beds baths deposit rate status : Apartment =
    let apart = { UnitNumber = nbr; Bedrooms = beds; Bathrooms = baths; SecurityDeposit = deposit; MonthlyRate = rate; Status = status }
    apart

let a399475 = createApartment "101" 2 2.00 650 1150 OccupancyStatus.Available
let a508293 = createApartment "102" 1 1.00 500 950 OccupancyStatus.NeedsRepair
let a729397 = { a508293 with UnitNumber = "103"; Status = OccupancyStatus.Available }
let a809387 = createApartment "104" 3 2.00 850 1350 OccupancyStatus.Occupied
let a486360 = { a508293 with UnitNumber = "105"; Status = OccupancyStatus.Available }
let a273004 = { a399475 with UnitNumber = "106"; Bathrooms = 1.00; MonthlyRate = 1050 }

showApartment a399475
showApartment a508293
showApartment a729397
showApartment a809387
showApartment a486360
showApartment a273004

do Application.Run apartmentRental

This would produce:

Records and Enumerations

In the same way, you can manipulate the enumerated label in any appropriate way.

     
     
 

Home Copyright © 2015 FunctionX Home