F# Example: Compound Interest

 Introduction
 This is an example of a function that takes a tuple and returns a pair. The example calculates the compound interest of a loan.
```// Example of a function that takes a tuple with 4 items and returns a pair
// Compound Interest: (Principal, Interest Rate, Periods(in years, frequency)
//      => (Future Value, Interest Earned)
let prepareLoan (principal, interestRate, periods, frequency) =
let mutable freq = 0.00;
let rate = interestRate / 100.00;

match frequency with
| 1 -> freq <- 12.00
| 2 -> freq <-  4.00
| 3 -> freq <-  2.00
| _ -> freq <-  1.00

(*    if frequency = 1 then
freq <- 12.00
elif frequency = 2 then
freq <-  4.00
elif frequency = 3 then
freq <-  2.00
else
freq <-  1.00*)

let i = rate / freq;
let n = freq * periods

let futureValue = principal * ((1.00 + i) ** n);
let interestEarned = futureValue - principal;
(futureValue, interestEarned)

let result1 = prepareLoan (16500.00, 12.75, 5.00, 1);
printfn "%A" result1;
printfn "Future Value:    %.02F" (fst result1);
printfn "Interest Earned: %.02F" (snd result1);
printfn "----------------------------------------";
let result2 = prepareLoan (16500.00, 12.75, 5.00, 2);
printfn "%A" result2;
printfn "Future Value:    %.02F" (fst result2);
printfn "Interest Earned: %.02F" (snd result2);```

 Home Copyright © 2015 FunctionX Home