Home

F# Arrays: The Sum of Numeric Members

   

Description

The sum() function is used to calculate the total of all the items of an array. The signature of that function is:

Array.sum : ^T [] -> ^T

This function takes one argument as the array that holds the values. Here is an example of calling the Array.sum() function:

type Employee = {
    EmployeeNumber : string
    FirstName      : string
    LastName       : string
    HourlySalary   : double }

let employees = [| { EmployeeNumber = "8022-3840"; FirstName = "Mark";  LastName = "Plant";  HourlySalary = 24.55 };
                   { EmployeeNumber = "5840-2497"; FirstName = "Carol"; LastName = "Mylans"; HourlySalary = 16.25 };
                   { EmployeeNumber = "2081-7008"; FirstName = "Maria"; LastName = "Pappas"; HourlySalary = 22.75 };
                   { EmployeeNumber = "2080-4813"; FirstName = "James"; LastName = "Alexanders"; HourlySalary = 22.25 }; |]

type PayrollPreparation(number, times) =
    let mutable nbr = number;
    let mutable tms = times;
    member this.EmployeeeNumber with get() = nbr and set(value) = nbr <- value;
    member this.TimesWorked with get() = tms and set(value) = tms <- value;
    member this.PaySummary() : float array =
        let mutable regularTime = 0.00
        let mutable overtime = 0.00
        let mutable regularAmount = 0.00
        let mutable overtimeSalary = 0.00
        let mutable overtimeAmount = 0.00
        
        let totalTime = Array.sum times
        
        let empl = Array.find (fun (empl : Employee) -> empl.EmployeeNumber = nbr) employees

        overtimeSalary <- empl.HourlySalary * 1.50

        // If the employee worked under 40 hours, there is no overtime
        if totalTime < 40. then
            regularTime <- totalTime
            regularAmount <- empl.HourlySalary * regularTime
            //overtime <- 0.00
            //overtimeAmount <- 0.00
            [| regularTime; 0.00; regularAmount; 0.00; regularAmount |]
        // If the employee worked over 40 hours, calculate the overtime
        else //if totalWeekTime >= 40. then
            regularTime <- 40.
            regularAmount <- empl.HourlySalary * 40.
            overtime <- totalTime - 40.
            overtimeAmount <- overtime * overtimeSalary
            [| 40.; overtime; regularAmount; overtimeAmount; regularAmount + overtimeAmount |]

// let pp = PayrollPreparation("5840-2497", [| 6.0; 7.5; 8.0; 6.5; 7.5; 0.0; 0.0 |]);
// let pp = PayrollPreparation("8022-3840", [| 8.50; 9.50; 10.00;  8.50; 9.50; 0.0; 0.0 |]);
let pp = PayrollPreparation("2080-4813", [| 8.50; 9.50; 10.50; 10.00; 9.00; 0.0; 0.0 |]);

let empl = Array.find (fun (empl : Employee) -> empl.EmployeeNumber = "2080-4813") employees
     
     
 

Home Copyright © 2012-2015, FunctionX Home