Programming Praxis – Excel Columns

In today’s Programming Praxis exercise our task is to write two functions to convert numbers to and from Excel’s letter-based column names. Let’s get started, shall we?

A quick import:

import Data.Char

The easiest way to covert numbers to Excel notation is recursively. I also wrote a version that uses an unfold to mirror the single fold below, but this version is more concise.

toExcel :: Int -> String
toExcel 0 = ""
toExcel n = toExcel d ++ [chr $ m + 65] where (d,m) = divMod (n - 1) 26

Converting back to numbers is even easier and can be done in a single fold.

fromExcel :: String -> Int
fromExcel = foldl (\a x -> 26 * a + ord x - 64) 0

Some test cases:

main :: IO ()
main = do print $ toExcel   1 == "A"
          print $ toExcel  26 == "Z"
          print $ toExcel  27 == "AA"
          print $ toExcel 256 == "IV"
          print $ fromExcel  "A" ==   1
          print $ fromExcel  "Z" ==  26
          print $ fromExcel "AA" ==  27
          print $ fromExcel "IV" == 256
          print $ all (\n -> n == (fromExcel . toExcel) n) [1..2^16]

Everything seems to be working correctly.

About these ads

Tags: , , , , , , , ,

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: