html css xml generation library in haskell
Few days ago I hacked around a little library for generating web pages in haskell.
I want to talk about it a little because it done in a 'type-oriented' way i.e. i wrote the algebraic datatypes first, and then proceeded with the 'code' that does anything. Having watched a few videos on category theory for hackers, this means i defined objects (in the category theory sense) first, and then wrote morphisms to translate between them (functions in the haskell).
I started with the XML type.
As can be seen, it's a thing, that contains other things (elements). These things can have some attached key-value pairs (attributes), and also a list of other those things (it's a recursive structure), or a piece of text. In other words, it's a tree, with the leaves being text, and the nodes can have attached key-value pairs.HTML is also a tree like XML, but has a greater variety of nodes. as listed in the definit of Element. There are things like breaks, horizontal rules, 'generic' containers of things (div's, spans'), and order/unordered lists, and tables, and paragraphs, and just plain text.
I have included a very simple definition inside there, called Rule, that views CSS has rules of the form describining query paths and key-value attributes.
I wish to in the future put in a more sophisticated definition of CSS, that begins with the CSS box model. The beginnings of this:
So next i want a function that converts from a HTML type that converts to an XML type
Haskell pattern matching made this straigt-forward, the compiler errors guided alont to the right outcome, along with a few helper functions, like el, that i put in to make the code less verbose.Next, a function to convert XML to a string (the ascii text that is the output .html file).
So there it is, typed functional programming pushes you in the direciton of 'cleanly' understanding what you're doing (the use of algebraic datatypes), and then helping in guiding you correctly transforming between these tree structures. You structure your program as translation between different kinds of tree structures.
The End
Comments
Post a Comment