Programming Praxis – Translate CSV To HTML

In today’s Programming Praxis exercise, our goal is to translate a csv file to an HTML table. Let’s get started, shall we?

We will be using the Text.CSV library to read in the csv file.

import Text.CSV
import Text.Printf

Converting the rows to a table consists of doing pretty much the same thing three times: the content is transformed in some way and surrounded by two html tags. Surprisingly, Haskell was not able to correctly figure out the type of the wrap function, complaining about an ambiguity. Presumably this is caused by a combination of printf, which is pretty polymorphic in and of itself and using the wrap function to process a [[String]], [String] and [Char], repsectively. Oh well, having to manually specify the type is not the end of the world.

toTable :: [[String]] -> String
toTable = wrap "table" unlines . wrap "tr" concat $ wrap "td" id id where
    wrap :: String -> ([b] -> String) -> (a -> b) -> [a] -> String
    wrap tag combine f xs = printf "<%s>%s</%s>" tag (combine $ map f xs) tag

All that’s left to do is to read in the csv file and call the toTable function if it was succesfully parsed.

main :: IO ()
main = putStrLn . either show toTable =<< parseCSVFromFile "test.csv"
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: