Programming Praxis – Chronological Listing Of Exercises

In today’s Programming Praxis exercise our goal is to replicate a script Phil wrote to generate chronological and reverse chronological lists of all of his posts. He did it in 24 lines of AWK, so let’s see how Haskell measures up.

Some imports:

import Data.List
import Data.List.Split
import Text.Printf
import Text.Regex.Posix

We need a function to display the name of a month.

toMonth :: Int -> String
toMonth m = chunk 3 "JanFebMarAprMayJunJulAugSepOctNovDec" !! (m - 1)

Generating the html for a post is roughly the same as in his version, save for the fact that I removed a bit of duplication in the links.

item :: [[String]] -> String
item xs = printf
    "<tr><td>%s</td><td>%02s %s %s</td><td>%s: %s</td>\
    \<td>%s%s<a href=\"http://programmingpraxis.codepad.org/%s\">\
    \codepad</a></td></tr>"
    (g "number") (g "pubday") (toMonth . read $ g "pubmon") (g "pubyear")
    (link "" (g "title")) (g "blurb") (link "" "exercise")
    (link ("/" ++ g "soln") "solution") (g "codepad")
    where g x = maybe "" last $ find ((== x) . head) xs
          link :: String -> String -> String
          link = printf "<a href=\"/%s/%02s/%02s/%s%s/\">%s</a>"
                 (g "pubyear") (g "pubmon") (g "pubday") (g "file")

Generating a list of items is pretty self-explanatory: separate the blocks, filter out the posts, parse the properties and generate the necessary html.

items :: String -> [String]
items = map (item . map (splitOn "\t") . lines) .
        filter (=~ "^number\t[1-9][0-9]*$") . splitOn "\n\n"

All that's left to do is sort the items as required and put them in a table. Like the original implementation, this version requires that the file containing the list is sorted chronologically.

listing :: ([String] -> [String]) -> String -> String
listing f xs = "<table cellpadding=\"10\">" ++
               concat (f $ items xs) ++ "</table>"

Let's see if everything works:

main :: IO ()
main = do x <- readFile "praxis.info"
          putStrLn $ listing id x
          putStrLn $ listing reverse x

Yup. And at 15 lines, I think I'll continue to use Haskell for my text munging needs.

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: