Tuesday, April 19, 2011

Reflection tools for F#

I went to the fabuluous CodeConf 2011 (view slides, recaps here, here, and here) and the first talk was "Tinker Fairy" Dr. Nic telling us to build tools to do stuff that we don't want to remember later. Then build tools to build those tools -- tool tools.

One of the neat modern takes on Lisp s-expressions in modern virtual machines like the CLR is Reflection. At least, I think that it will be useful in reversing Lisp macros and expressions into the F#/OCAML equivalents.

Dr. Jon Harrop gives a terse but informative example in his book Visual F# 2010 for Technical Computing.

First, we want a union type which represents (i.e. abstracts away) the F# type system:

Next, we want a (recursive) function (called, straightforwardly enough, type_of) that reflects (using FSharpType) and translates a given System.Type object into one of the 'a ty union types defined previously:

This then allows us to emit the following two liner which can parse objects such as the List.fold function! (Note: everything after the ;; is the F# Interactive response.)

Neat stuff! I've a thousand or two lines of Lisp to look at, so this is not something I want to have to remember later.

No comments: