A Spoonful of Metaprogramming
6/22/2022
(is good for what ails you)
Note:
This post was written as a work presentation around ~2019 or so. I like the ideas here still, so it stays on the blog (Neptune, 2025)
What?
A language that supports metaprogramming is a language that supports programming itself. Here I focus on two aspects:
- Code is data, data is code
- The language itself is programmable
Why?
Fun mostly. And to expand the number of operations we can perform without thinking about them.
Manipulating Functions

There are 3 parts of a function in R.
Formals
Formals are a list, so we can treat them as such.
Body
The function body is an expression.
A function can even find its own definition.
Environments
Environments are the scope in which the function is evaluated.
Manipulating Expressions

We can capture code without evaluating it using expr().
Quasiquotation = quotation + unquotation. It is everywhere in R.
Under the hood we delay evaluation until we have the proper environment. In this case, the awaited environment is the dataset mtcars. This is tidy evaluation: quasiquotation + quosures + data masks.
TidyEval

Tidyeval is practical: unquoted column references, scoped evaluation, and flexible data-masked functions.
A helper to capture original argument names for plot labels, then a simple plotting wrapper:
Substitutions

We can coerce expressions to strings, manipulate them, and parse back.
Make code as data, then unquote it back into code.
Pipes are just syntax sugar over nested calls.
Define your own infix operators.
An example: replicate Clojure threading macros
In Clojure:
A small R helper that emulates a threaded pipeline by stitching a string of %>% calls and evaluating it:
The big idea: we are not limited to the language designer. We can become the language designer.
Generating Code with R

It does not need to be R code that we generate. dbplyr translates dplyr pipelines to SQL, for example.
Shiny generates HTML, CSS, and JS.
Other things to check out

- tidyeval
- rlang
- how calls work
- how formulas work
- how symbols work
- how interpreters work
- how compilers work
Resources to look into
- Advanced R
- Thomas Mailund's books on R
- Lisp family programming languages
- The Documentation