Home

F# Collections: Choosing a Sub-Array

   

Description

If you have an array with values that can be distinguished in categories, you can create a sub-array of items that respond to a particular criterion. To support this operation, the Array class provides a method named choose.

Its signature is:

Array.choose : ('T -> 'U option) -> 'T [] -> 'U []

This function takes two arguments. The first argument is a matching statement that specifies a condition by which some values will be selected. The second argument is an array that holds the values. Here is an example of calling the function:

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

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

let apartments = [|
    { UnitNumber = "101"; Bedrooms = 2; Bathrooms = 2.00; SecurityDeposit =  650; MonthlyRate = 1150; Status = OccupancyStatus.Available   }
    { UnitNumber = "102"; Bedrooms = 1; Bathrooms = 1.00; SecurityDeposit =  500; MonthlyRate =  950; Status = OccupancyStatus.NeedsRepair }
    { UnitNumber = "103"; Bedrooms = 1; Bathrooms = 1.00; SecurityDeposit =  500; MonthlyRate =  925; Status = OccupancyStatus.Available   }
    { UnitNumber = "104"; Bedrooms = 3; Bathrooms = 2.00; SecurityDeposit =  850; MonthlyRate = 1350; Status = OccupancyStatus.Occupied    }
    { UnitNumber = "105"; Bedrooms = 2; Bathrooms = 1.00; SecurityDeposit =  550; MonthlyRate = 1150; Status = OccupancyStatus.Available   }
    { UnitNumber = "106"; Bedrooms = 3; Bathrooms = 2.00; SecurityDeposit = 1350; MonthlyRate =  850; Status = OccupancyStatus.Available   }
    { UnitNumber = "107"; Bedrooms = 3; Bathrooms = 2.00; SecurityDeposit = 1285; MonthlyRate =  850; Status = OccupancyStatus.NotReady    }
    { UnitNumber = "108"; Bedrooms = 1; Bathrooms = 1.00; SecurityDeposit =  885; MonthlyRate =  500; Status = OccupancyStatus.Available   }
    { UnitNumber = "109"; Bedrooms = 2; Bathrooms = 2.00; SecurityDeposit = 1150; MonthlyRate =  650; Status = OccupancyStatus.Available   }
    { UnitNumber = "110"; Bedrooms = 1; Bathrooms = 1.00; SecurityDeposit =  895; MonthlyRate =  500; Status = OccupancyStatus.Available   }
 |]

let choose = Array.choose (fun (apart : Apartment) -> 
    match apart.Bedrooms with
    | 1 -> Some(apart)
    | _ -> None) apartments
     
     

Home Copyright © 2012-2015, FunctionX Home