Idempotent Template Haskell

Yesterday I was looking for a way to have some Template Haskell code generate a definition for a certain identifier if and only if such a definition did not already exist. Essentially I want to be able to call the code multiple times but have it generate something only once. This turns out to be extremely easy but non-obvious, so I thought I’d write it here for posterity. The trick is that reify throws an error if called on an identifier that doesn’t exist, and recover can be used to catch TH errors. Thus:


recover (generateBinding n) (reify n >> return [])

which uses generateBinding n to “recover” from the error of n‘s non-existence.

About Brent

Associate Professor of Computer Science at Hendrix College. Functional programmer, mathematician, teacher, pianist, follower of Jesus.
This entry was posted in haskell and tagged , , , . Bookmark the permalink.

2 Responses to Idempotent Template Haskell

  1. How general can you make reify?

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.