Home > Uncategorized > How would you solve Ayendes tax calculation exercise?

How would you solve Ayendes tax calculation exercise?

Ayende posted a tax calculation exercise that he apparently uses to test candidates when hiring. I wondered if I could write down a solution that was clear and without spending much time. This was my spontaneous attempt:

let rec tax money =

    if money <= 5070.0 then

        money * 0.1

    else if money <= 8660.0 then

        (money – 5070.0) * 0.14 + tax 5070.0

    else if money <= 14070.0 then

        (money – 8660.0) * 0.23 + tax 8660.0

    else if money <= 21240.0 then

        (money – 14070.0) * 0.30 + tax 14070.0

    else if money <= 40230.0 then

        (money – 21240.0) * 0.33 + tax 21240.0

    else

        (money – 40230.0) * 0.45 + tax 40230.0

 

assert(tax 5000.0 = 500.0)

assert(tax 5800.0 = 609.2)

assert(tax 9000.0 = 1087.8)

assert(tax 15000.0 = 2532.9)

assert(tax 50000.0 = 15068.1)

 

It was a bit of pain to insert the correct numbers in the right places. Not really satisfying. I tried another one; more data driven this time.

 

let tax_rates =    

    [

    ((0.0,5070.0), 0.10);

    ((5070.0,8660.0), 0.14);

    ((8660.0,14070.0), 0.23);

    ((14070.0,21240.0), 0.30);

    ((21240.0,40230.0), 0.33);

    ((40230.0,System.Double.MaxValue), 0.45)

    ]

 

let tax2 money =

    seq {

        for (inf,sup), rate in tax_rates do

            if money > inf then

                yield ((min sup money) – inf) * rate

    } |> Seq.sum

 

assert(tax2 5000.0 = 500.0)

assert(tax2 5800.0 = 609.2)

assert(tax2 9000.0 = 1087.8)

assert(tax2 15000.0 = 2532.9)

assert(tax2 50000.0 = 15068.1)

 

Using sequence expressions seems a bit overkill actually and thus not the perfect solution either. How would you solve it?

Advertisements
Categories: Uncategorized
  1. No comments yet.
  1. No trackbacks yet.

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

%d bloggers like this: