Home

F# Collections: Applying a Condition to All Items

   

Description

To let you apply the same condition to all elements of an array, the Array class provides the forall() method. Its signature is:

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

The first of the two arguments is a Boolean function that applies a condition to each member of the array of the second argument. If all members of the array respond to the condition, the function returns true. If at least one member of the array doesn't apply to the condition, the function returns false. 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 areAllItemsDiscounted = Array.forall (fun (si : StoreItem) -> si.DiscountRate > 0.00) storeItems
     
     

Home Copyright © 2012-2015, FunctionX Home