I haven't written anything in a while. But after seeing the metaprogramming video on Computerphile the other day I felt the urge to write about Lisp again, so I decided to do a small series of posts on fun/useful little Common Lisp macros I've made over the past couple of years.

The first macro we'll look at is gathering :

( defmacro gathering ( &body body ) "Run `body` to gather some things and return a fresh list of them. `body` will be executed with the symbol `gather` bound to a function of one argument. Once `body` has finished, a list of everything `gather` was called on will be returned. It's handy for pulling results out of code that executes procedurally and doesn't return anything, like `maphash` or Alexandria's `map-permutations`. The `gather` function can be passed to other functions, but should not be retained once the `gathering` form has returned (it would be useless to do so anyway). Examples: (gathering (dotimes (i 5) (gather i)) => (0 1 2 3 4) (gathering (mapc #'gather '(1 2 3)) (mapc #'gather '(a b))) => (1 2 3 a b) " ( alexandria:with-gensyms ( result ) ` ( let ( ( ,result nil ) ) ( flet ( ( gather ( item ) ( push item ,result ) item ) ) ,@body ) ( nreverse ,result ) ) ) )

As the docstring mentions, sometimes you'll encounter procedural code that iterates over things but doesn't return any results (CL's maphash and Alexandria's map-permutations are two examples). The gathering macro provides an easy way to plug into the guts of the iteration and get a list back. The docstring describes how to use the macro, but there's a couple of extra things to note before we move on.

I'm aware that the (let ((,result nil)) ...) in the macro could be simplified to (let (,result) ...) because bindings without an initial value default to nil . I just personally dislike that style and prefer to be explicit about the initial values, even when they're nil .

The flet ed function that actually does the gathering is named as the symbol gather , not a gensym. Some folks will dislike that because it captures the function name. I don't mind it. I consider that behavior part of the intended/documented API of the macro, and because the symbol gather is coming from the macro's package you'll need to import it (or package qualify it) to access it.

If you want to provide a bit more safety here you could potentially define a vanilla function for gather like this:

( defun gather ( value ) "Gather `value` into the result. Must be called from inside `gathering`." ( error "GATHER be called from within a GATHERING macro." ) )

Doing this would mean calling gather outside a gathering block would signal an error, and someone defining their own gather function (which could accidentally get shadowed by the macro's flet later) would get a warning about redefining the function, which would hopefully make them realize the potential conflict earlier.

Of course you could also write your own version of gathering that takes in a symbol to use for the function, if you prefer. That would avoid all of these issues, at the cost of making every (gathering ...) slightly more verbose.

My actual implementation of this macro uses a simple queue data structure instead of a list to avoid having to reverse the result at the end, but I didn't want to include an extra dependency just for this blog post.

Feel free to skip this section. It gets a little bit into the weeds.

One potential optimization we could make is to declare the gather function to have dynamic extent. This means that some implementations (e.g. SBCL) can stack allocate the closure and save a heap allocation.

( defmacro gathering-dynamic-extent ( &body body ) ( alexandria:with-gensyms ( result ) ` ( let ( ( ,result nil ) ) ( flet ( ( gather ( item ) ( push item ,result ) item ) ) ( declare ( dynamic-extent #'gather ) ) ,@body ) ( nreverse ,result ) ) ) )

Whether this matters much depends on the usage patterns. If you use gathering with some code that typically gathers no elements (and only occasionally gathers a few), you won't have to heap allocate anything for the common cases, and things will be a little more efficient. If you typically gather a bunch of things then you're heap allocating all the cons cells anyway, so allocating the closure wouldn't be a big deal.

If you want to actually see the stack allocation in action, it might be a little trickier than you think. SBCL is pretty smart about inlining things, so it might not allocate the closure at runtime at all, even without the dynamic-extent declaration:

( disassemble ( lambda ( ) ( gathering ( mapc #'gather ' ( 1 2 3 ) ) ) ) ) NIL

Here SBCL knows what mapc is and expands it inline (notice how there's no function call to mapc ). It then realizes it never needs to allocate a closure for gather at all, it can just inline that too! All the allocation stuff in that disassembly is for the push ing of new cons cells (to convince yourself of this, run (disassemble (lambda (&aux result) (push 1 result) result)) and compare the assembly).

But if we make our own version of mapc :

( defun my-mapc ( function list ) ( mapc function list ) )

Now we can see a difference, because SBCL won't necessarily know it can stack allocate the closure unless we tell it. Here's what the disassembly looks like without the dynamic-extent inside gathering :

( disassemble ( lambda ( ) ( gathering ( my-mapc #'gather ' ( 1 2 3 ) ) ) ) ) NIL

Now we can see it's allocating the closure on the heap (note the SB-VM:FUNCTION-LAYOUT ).

If we add the dynamic-extent back into gathering :

( disassemble ( lambda ( ) ( gathering-dynamic-extent ( my-mapc #'gather ' ( 1 2 3 ) ) ) ) ) NIL

Much nicer. However, this optimization comes with a price: safety.

The gather closure should never be called outside of the gathering block that defines it. As the docstring says: it would be useless to do so anyway, because the result has already been returned. But what would happen if the user accidentally calls the closure? Let's try it out, first on the original version without the dynamic-extent declaration:

( defparameter *f* nil ) ( defun leak ( function ) ( setf *f* function ) ) ( gathering ( leak #'gather ) ) ( funcall *f* 1 )

Here the closure is heap-allocated, so calling it later is fine (if useless). But what happens if we try our optimized version?

( gathering-dynamic-extent ( leak #'gather ) ) ( funcall *f* )

Things get even worse if you're brave (foolish) enough to be running with (declaim (safety 0)) :

( gathering-dynamic-extent ( leak #'gather ) ) ( funcall *f* )

The moral of this story is that although we can optimize for a little bit of speed, it comes at a price that might not be worth paying.

Here's an exercise for you: make the original heap-allocated version signal an error (with a nice error message) when called outside of its gathering block, instead of silently doing something useless.

Let's finish up by looking at some places where I've found this macro to be handy. I won't go into too much depth about the individual pieces of code, but feel free to ask if you have questions.

First up, an example from my Project Euler utils.lisp file:

( defun pandigitals ( &optional ( start 1 ) ( end 9 ) ) "Return a list of all `start` to `end` (inclusive) pandigital numbers." ( gathering ( map-permutations ( lambda ( digits ) ( unless ( zerop ( first digits ) ) ( gather ( digits-to-number digits ) ) ) ) ( irange start end ) :copy nil ) ) )

This is a prime example of where Alexandria's map-permutations not returning anything is annoying, but also shows how gathering provides you a little more flexibility. Even if map-permutations returned a list of results, we'd still need to filter out the ones that start with zero. With gathering we can avoid collecting the unneeded results at all by simply not calling gather on them.

Next is an easy way to convert a hash table to lists of (key value) :

( defun hash-table-contents ( hash-table ) "Return a fresh list of `(key value)` elements of `hash-table`." ( gathering ( maphash ( compose #'gather #'list ) hash-table ) ) )

Because gather is a flet ed function we can use it like any other function. Here we compose it with list and pass it off to maphash (which, for some reason, doesn't return its results).

We'll end with a triangle-generation function from my procedural art bot:

( defun generate-universe-balancing ( depth ) ( gathering ( labels ( ( should-stop-p ( iteration ) ( or ( = depth iteration ) ( and ( > iteration 6 ) ( randomp ( map-range 0 depth 0.0 0.05 iteration ) #'rand ) ) ) ) ( recur ( triangle &optional ( iteration 0 ) ) ( if ( should-stop-p iteration ) ( gather triangle ) ( map nil ( rcurry #'recur ( 1+ iteration ) ) ( split-triangle-self-balancing triangle ) ) ) ) ) ( map nil #'recur ( initial-triangles ) ) ) ) )

This is used to generate the triangles for images like this: