The best kittens, technology, and video games blog in the world.

Sunday, July 30, 2006

XML-oriented programming with CDuce

Image from flickr by Tom Harpel, CC-BY.
I don't think many people believed me when I was talking about language-level support XML. But they actually do make languages for XML-oriented programming, and maybe we can borrow some of their ideas. One of such languages is CDuce, which is based mostly on OCaml. So the first thing we can do is loading XML file:
let posts = load_xml "http://taw:password@del.icio.us/api/posts/all";;
Wow, it wasn't that bad. Unfortunately if we do it like that, posts is going to have type AnyXml and CDuce's type system won't let us code without explicitly dealing with weird kinds of data. So unfortunately we need to specify types:
type Post=<post href=String description=String ..>[];;
type Posts=<posts ..>[Post*];;

let posts :? Posts = load_xml "http://taw:password@del.icio.us/api/posts/all";;
So we have a list of all my del.icio.us entries.
let format_posts (Posts -> Any)
 <posts ..>items ->
 <ul>(map items with
   <post description=dsc href=href ..>_ ->
   <li>[<a href=href>dsc]
 );;
The first line defines a function name and its type. Functions can have types Any -> Any, but then we'd have to catch "other" patterns. So the type system is only moderately annoying here. The rest should become intuitive if you look at it for 5 minutes ;-) And let's just apply the function and print the results:
let the_list = format_posts posts;;

dump_to_file "out.html" (print_xml
 <html>[
   <head>[
     <title>"del.icio.us summary magically generated by CDuce"
   ]
   <body>[
     <h3>"List"
     the_list
   ]
 ]
);;
And here we are, with nicely formatted XHTML output. Of course it has more fancy features, like queries, joins and whatnot. Now the question is - is it worth it, additng XML support at language level. I would say yes. XML processing is something that most programs either already do, or would do if it was easier, like when parsing configuration files. And easy things should be easy.

1 comment:

Anonymous said...

Note that for attributes, you can write href instead of href=href (in patterns and expressions).