Template Haskell Example

13 AUG 2003

Template Haskell is a sophisticated macro system for Haskell. It is included with GHC 6.0 and above. One of the first uses people are finding for Template Haskell is the ability to capture patterns that were previously beyond the scope of Haskell's type system.

One of the convenient things we do in Python (for instance) is to unpack a list into a tuple like this:

(foo, bar, baz) = list_of_stuff

now this, while convenient, is a mess from a typing standpoint, and Haskell's type system won't let you do it. But you could imagine writing

let (foo, bar, baz) = (list_of_stuff !! 0, list_of_stuff !! 1, list_of_stuff !! 2)

to do the same thing, and that would work fine. With Template Haskell, you can automate this sort of thing:

let (foo, bar, baz) = $(tuple 3) list_of_stuff

Pretty cool.

Here's the code for the tuple function:

tuple :: Int -> ExpQ

tuple n = [|\list -> $(tup (exprs [|list|])) |]


    exprs list = [infixE (Just (list))

		         (var "!!")

		         (Just (lit (Integer (toInteger num))))

		    | num <- [0..(n - 1)]]

More information: