Structures in Emacs Lisp

Chris Wellons over at Null Program has another great post. It considers how to define and use structures in Emacs Lisp. What I like most about the post is that it starts with the obvious solution of using a list to hold the structure and accessing the elements of the structure with the nth function or something similar but notices the problems that such a strategy can bring.

One such problem is that it’s hard to remember which slots in the list corresponds to which items in the structure. This is especially hard on readers but can also trip up the original author. Another issue with using the nth strategy is that it effectively freezes the slot positions and makes it hard to modify the program.

To solve these problems, Wellons introduces some accessor functions to access the structure items by name. Then he does the same thing for setting the functions by making them settable with setf. At that point, he’s got a pretty nice solution but has written a lot of boiler plate. He observes that a natural solution is to write a macro to write all the boiler plate and says that Emacs, of course, has already done this with the cl-defstruct macro.

Most Elisp programmers have probably used cl-defstruct but never thought much about why it exists or how it works. That’s what’s great about Wellon’s post: it shows how cl-defstruct grows naturally out of finding a solution for a common need and the problems that the obvious solution to that need entails.

The rest of Wellon’s post considers changes coming in Emacs 26. If you do any Elisp programming at all, you should definitely read this post. It’s full of good information—way more than I’ve discussed here—and news of what we can expect, as far as structures are concerned, in Emacs 26.

This entry was posted in General and tagged . Bookmark the permalink.