Home

F# Arrays: Filtering Items

   

Description

Filtering items consists of applying a condition to the values of the array. The values that respond to the condition are selected and stored in a new array that is the result of the operation. To support this operation, the Array class provides the filter() method. Its signature is:

Array.filter : ('T -> bool) -> 'T [] -> 'T []

This method takes two arguments and returns an array. The first argument is a condition to apply to each value of the array that is the second argument. Here is an example:

Here is an example:

type StoreItem(number, make, category, subcategory, name, size, price, discrate) =
    let mutable nbr = number
    let mutable mk = make
    let mutable cat = category
    let mutable sub = subcategory
    let mutable nm = name
    let mutable sz = size
    let mutable prc = price
    let mutable rate = discrate

    member this.ItemNumber   with get() = nbr  and set(value) = nbr  <- value
    member this.Manufacturer with get() = mk   and set(value) = mk   <- value
    member this.Category     with get() = cat  and set(value) = cat  <- value
    member this.SubCategory  with get() = sub  and set(value) = sub  <- value
    member this.ItemName     with get() = nm   and set(value) = nm   <- value
    member this.ItemSize     with get() = sz   and set(value) = sz   <- value
    member this.UnitPrice    with get() = prc  and set(value) = prc  <- value
    member this.DiscountRate with get() = rate and set(value) = rate <- value
    member this.GetDiscountAmount() = this.UnitPrice * this.DiscountRate / 100.00
    member this.MarkedPrice() = this.UnitPrice - this.GetDiscountAmount();
    new(number, make, category, subcategory, name, size, price) = StoreItem(number, make, category, subcategory, name, size, price, 0.00) 

let storeItems = [| StoreItem("441180", "Ralph Lauren", "Girls", "Shirts", "Girls 2-6X Short-Sleeved Mesh Polo Shirt", "3/3T", 34.95)
                    StoreItem("292915", "Kenneth Cole", "Women", "Dresses", "Three-Quarter Sleeved Dress", "L", 145.50, 20.00)
                    StoreItem("479160", "Polo Ralph Lauren", "Men", "Pants", "Classic Straight-Leg Jeans", "33W - 32L", 84.85)
                    StoreItem("561150", "Kenneth Cole", "Women", "Dresses", "Three-Quarter Sleeved Dress", "XS", 145.50, 20.00)
                    StoreItem("689771", "Calvin Klein", "Men", "Pants", "Straight Leg Jean in Black Wash", "38/30", 45.00)
                    StoreItem("570810", "Nautica", "Boys", "Sweaters", "Boys 2-7 Cashmere Cable V-neck Sweater", "2T/3T", 145.00)
                 |];

let womenClothes = Array.filter (fun (si : StoreItem) -> si.Category = "Women") storeItems
     
     

Home Copyright © 2012-2015, FunctionX Home