Home

Records & Pattern Matching

   

Description

Various combinations of objects of a record can be used in pattern matching to find out what combination is valid for a particular scenario. The pattern to compare should be a sample object. The options can be various objects to which to compare the pattern. You can then take action based on the option that matches the pattern. Here is an example:

open System
open System.Windows.Forms

(* This is a record type representing employees who work in a commercial bank.
   In this simple example of a record, each employee record determines
   where the employee is currently working (today) in the office or from home.*)
type Employee = {
    EmployeeNumber : string
    WorkFrom       : string }

(* These records indicate where the employee is working today
   Notice that the same employee number can have more than one record but
   working either in the office or from home (on different days. *)
let e279374o = { EmployeeNumber = "279-374"; WorkFrom = "Office" }
let e635753o = { EmployeeNumber = "635-753"; WorkFrom = "Office" }
let e279374h = { EmployeeNumber = "279-374"; WorkFrom = "Home"   }
let e826846o = { EmployeeNumber = "826-846"; WorkFrom = "Office" }

let evaluate (empl : Employee) =
    let mutable employeeCanProcessAccount = false
    (* This pattern matching is meant to find out where the employee is 
       working today. Employees are not allowed to modify customers' 
       accounts when they work from home. So even if an employee is a 
       manager but working from home, he is not allowed to open 
       new bank accounts or to make changes on existing bank accounts. *)
    match empl with
    | { EmployeeNumber = "279-374"; WorkFrom = "Office" } -> employeeCanProcessAccount <- true
    | { EmployeeNumber = "635-753"; WorkFrom = "Office" } -> employeeCanProcessAccount <- true
    | { EmployeeNumber = "279-374"; WorkFrom = "Home"   } -> employeeCanProcessAccount <- false
    | { EmployeeNumber = "826-846"; WorkFrom = "Office" } -> employeeCanProcessAccount <- true
    | _ -> employeeCanProcessAccount <- true
    
    employeeCanProcessAccount

let mutable result = evaluate e635753o

// Do some things here

result <- evaluate e279374h

// . . .
     
     
 

Home Copyright © 2015 FunctionX Home