Programming Praxis – Loan Amortization

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.

About these ads

Tags: , , , ,

2 Responses to “Programming Praxis – Loan Amortization”

  1. phimuemue Says:

    Is this ocaml?

  2. Remco Niemeijer Says:

    No. Like all the code on this blog so far, this piece of code is written in Haskell. Like F#, Haskell is a functional language, but there are a number of differences. You can learn more about it at http://en.wikipedia.org/wiki/Haskell_(programming_language) .

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


Follow

Get every new post delivered to your Inbox.

Join 35 other followers

%d bloggers like this: