Metaprogramming
What it is, how to use it, and why you should care
Slides available at: https://wbuchanan.github.io/stataConference2023
What it is
- Programs that write or modify programs
- Inputs are data, metadata, and/or sourcecode
- Processes Concept Classes used (see Damaševičius & Štuikys, 2008 for details):
- Code Generation
- Transformation
- Reflection
- Generalization
- Output is static or dynamic
How is it implemented in Stata?
Macros
- Macros can be used to compose syntax
- Evaluation of macros enables flexible composition
- Control evaluation with \ or
macval()
- Access metadata with extended macro functions
Mata Strings
- Use string variables to create and modify syntax
- Incorporate values stored in Stata macros as needed
- Mata function
stata()
can execute your code
- Mata classes persist across Stata commands
Dynamic Code Generation
Static Code Generation
Code Templates
Code Templates
Stata/Java "Reflection"
- Abstraction
- Time Savings
- Automation/Reproducibility
Remember
- Programs that write or manipulate other programs
- Use macros and Mata strings variables
- Proper use = reduced time and effort