Metaprogramming allows you to write a function that generates the boilerplate, and transparently use that function as if it's a brand new keyword in your programming language. That function in metaprogramming circles is called a "macro", not to be confused with C macros.
Stated another way: a macro = a function that takes as input the code you want to write, and provides as output code that your programming language can actually execute. (It's like a super miniature compiler.)
For example, let's pretend C is metaprogrammable.
Perhaps I want a new keyword "pfor" which is like "for" but executes the loop in parallel.
int x[20];
pfor(i = 0; i < 10; i++) {
x[2*i] = expensive(2*i);
x[2*i+1] = expensive(2*i+1);
}
Here, we assume "expensive" is some really expensive function that maybe might take several seconds to execute, which is why we want to parallelize it.This "pfor" is just a sort is pseudo code. In reality, you know how we would actually have to write this: make a loop in which we spawn 10 threads, set i to be a thread local variable in each, call a callback function in each thread
void thread_callback(int i){
x[2*i] = expensive(2*i);
x[2*i+1] = expensive(2*i+1);
}
and join the threads at the end. This would have the equivalent effect as our desired "pfor" keyword.In a metaprogramming language, we can add this keyword by just telling the compiler what code to generate any time it sees "pfor". We could write something like
macro pfor(var = init, cond, incr, body...) {
symbol callback = generate_random_symbol();
```
void $callback(int $var) {
$...body;
}
vector threads;
for($var = $init; $cond; $incr) {
threads.push(make_thread($callback, $var));
}
for(t in threads)
join_thread(t);
```
}
The triple ``` starts a template, and the $ escapes a template. We have to generate a fresh symbol for the callback name so that they don't collide when we use "pfor" multiple times.Now every time we use "pfor", the compiler will look at our homemade code generator function and write out the code for us.
So in effect by telling the compiler how "pfor" can be implemented in more basic code, we've added "pfor" to the language.
This isn't a separate tool however! It's not a pre-processor or anything like that. It's built in to the language (hence why it's a programming language paradigm).
Since macros in effect receive structured source code (basically an AST) as input, you can also do analysis of that code. For example, a macro to simplify algebraic expressions at compile-time.
Abstractions based on high-order functions also tend to allocate closures at run-time, so in practice you frequently get a performance penalty for their use.
High-order functions remove the need to use macros in some cases, but definitely don't replace all of them.
Is there anything you should do with macros that you can’t do with similar language features like higher order functions?
My concern with macros is that they are completely open-ended, so you can really do anything - and if you can do anything, then the language is not usefully defining a strict enough semantic structure. As an example, see the 'hygiene problem'.
I am providing language-level APIs for a complex web service, one in Python and one in Common Lisp. The service has dozens of operations, all of which are wrapped around a REST API that takes query strings and headers in its inputs, and produces very different outputs. Model for this is something like S3.
In most languages, I have two choices: I can push the complexity to the users, making them plug the query string values into a big map or option object; or I can write dozens of functions, most of which are boilerplate.
In Python I wrote dozens of functions (I obviously reused a set of central ones, but there's lots of scaffolding to do, e.g., translation of arguments from user types to strings appropriate HTTP headers). In Lisp I wrote a macro that operates on a set of query string and header inputs, and then defines a function appropriate for the user-level API. When I fix bugs in the macro, I automatically fix all of the functions.
The trade-off is that the macro is itself a function that's operating at two different semantic levels (pre- and post-compilation), and it might be challenging to read for newcomers to Lisps. But this let me hide all the nasty API complexity from my users while writing substantially fewer lines of code. New additions are a single defmacro line.
For example: we may want a macro which outputs the source it encloses, before execution:
CL-USER 12 > (defmacro my-loop (&body things)
`(progn
(pprint (list :doing-loop-with ',things))
(loop ,@things)))
MY-LOOP
CL-USER 13 > (my-loop for i from 1 upto 3 sum
(my-loop for j upto 3
sum (* i j)))
(:DOING-LOOP-WITH
(FOR I FROM 1 UPTO 3 SUM (MY-LOOP FOR J UPTO 3 SUM (* I J))))
(:DOING-LOOP-WITH (FOR J UPTO 3 SUM (* I J)))
(:DOING-LOOP-WITH (FOR J UPTO 3 SUM (* I J)))
(:DOING-LOOP-WITH (FOR J UPTO 3 SUM (* I J)))
36
A normal function can't do that, since it does not get source as an argument, but just sees the arguments values.Since a macro sees source, it can not only print it, but also simplify, transform, mutate, etc. the source.
One nice thing I've used macros for is reading and parsing files at compile-time, to bake-in data into programs. That way, the compiled programs just process stdio, without having to care about file paths, permission errors, parse errors, etc. (those all become compile errors)
So I am not sure, I will succeed at it, but I am saving your comment, to try when they are ready. 10 years might be doable. Probably depends how many more times they hit their head..
(And whether I can spark enthusiasm in them, but robots are fun..)
Metaprogramming is "programming programming". Consider "programming" as writing a series of steps for a computer to follow. Metaprogramming is writing a series of steps for a computer to follow to write a series of steps for a computer to follow.
When working with LISP, metaprogramming is just a normal way to program things that's built into the language. Rather than writing everything as a linear program as you would in conventional languages, you can write a program that "writes itself" (or modifies parts of itself).
While you could meta-program in many languages (using code generators and whatnot), in LISP this is easy because the programs themselves are written in a way that makes them easy to be manipulated by other parts of the program. This is why you'll see so many parentheses when looking at LISP code. The simplicity of the syntax is also what makes it so powerful.
Metaprogramming is a technique that often results in much shorter programs which can make single programmers very effective. The downside is that the higher level of abstraction (leaving ELI5 zone here, sorry) can make the workings of LISP programs quite opaque to newcomers as things seem a lot like magic. Therefore preserving the metaprogramming advantages in larger teams requires _especially_ good documentation and attention to design.
for i in 1 to 10 do printf("%d\n", i)
Becomes (through a preprocessor in this hypothetical system) valid C as: for(int i = 1; i <= 10; i++) { printf("%d\n", i); }
Now that's not too interesting, but it is a bit (subjective) nicer looping syntax than C's straight syntax. In the Lisp case, macros allow you to take an arbitrary set of values (the parameters to the macro) and produce some other value or values in their place. This could be just executing the code to get a kind of compile time evaluation: (hypotehtical-expression-evaluator-macro (complex-computation-that-gets-reused-100-times-but-takes-10-minutes-each-time))
Or it could be more transformative, like Lisp's loop macro that lets you write an Algol-ish loop instead of a lisp-y loop (or using recursion or other approaches): (loop for i from 1 to 10 do (print i))
Which gets transformed into some other valid Lisp code (not on my laptop so not in a position to actually show the result).David Moon's "Moon's Mark Down" is actually a pretty neat case of Lisp meta programming. He defines a macro defdot which will take a name for a particular directive for his markdown syntax and generate all the necessary functions so that things "just work". And when parsing, when a . is found at the start of a line, the correct handler is calculated and called. To add a new directive, you add a new defdot and that macro will create the relevant functions and register the new handler.
In other words: if your function is able to produce (+ 1 2), same function produces 3, when used as macro.
a lambda evaluates all it's args, a macro not.