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"
Tags: bonsai, code, csv, Haskell, html, kata, praxis, programming, table