Archive for May 12th, 2009

Programming Praxis – Loan Amortization

May 12, 2009

Today‚Äôs Programming Praxis problem is about loan amortization. For those of you who, like me, had no idea how to calculate that, here‘s a good step by step guide. Let’s begin.

First our import:

import Text.Printf

With a bit of simplification we can reduce the step-by-step guide to this:

amortize :: Fractional a => a -> a -> Int -> [(Int, a, a, a)]
amortize _ _ 0 = []
amortize b r l = (l - 1, prn, int, b') : amortize b' r (l - 1)
                 where int = b * r
                       prn = int / ((1 + r) ^ l - 1)
                       b' = b - prn

Creating a table is then simply a matter of printing the header, starting month and formatting the output:

amortization :: Double -> Double -> Int -> IO ()
amortization b r l = do
    putStrLn "Left Principal Interest   Balance"
    mapM_ table $ (l, 0, 0, b) : amortize b (r / 12 / 100) l
    where table (m, p, i, t) = printf "%4d %9.2f %8.2f %9.2f\n" m p i t

And to test our function:

main :: IO ()
main = amortization 10000 7 36

And that’s all there is to it.

Advertisements