Macros, Finally (Recurse Day 3)
Originally at https://notes.shaunagm.net/post/643406749078011904/macros-finally-recurse-day-3
When we left off, I’d written some rather ugly code that gave us the basic features of a madlibs program without using any macros. But the whole point of this project is to better understand lisp macros. So today I focused on refactoring my program to use macros instead.
Luckily Recurser Greg Hendershott has written a truly excellent guide to working with macros called Fear of Macros. I spent the morning reading through the first part of it and learning the basics. Then, I made a little macro that took the name and prompt for a madlibs “blank” (eg, “adjective” and “Give an adjective: “) and created the necessary code so that the user is shown the prompt, and their response is recorded with the variable name provided. I also went back and rescued some code Tristan and I had written to store previous inputs in a hash so we can reuse variables in our templates.
The code was already looking better, but I wanted more - I wanted the ability to create a bunch of story templates easily and then load the one I want by calling “tree-story” or “river-story” or “cat-story” from the interpreter. So I created a story-template macro that the blank macro was nested in. Here’s where I ran into the biggest trouble of the day. I just couldn’t figure out how to pass through the list which included the blank macros without executing them.
I took a break to pair with Recurser Pavan. Pavan was really interested in my project but had never used a lisp before, so we spent the whole hour just talking about how my code, and Lisp/Racket itself, works. Explaining to somebody else was a fantastic way for me to get clearer on the concepts, and when I returned to debugging afterwards, refreshed, it was fairly easy to figure out the problem. Basically, my macro was trying to pass the inner macro through to an existing function, rather than constructing the function itself. Here’s the final working code.
I’m really pleased with what I accomplished today, and grateful to both Greg and Pavan for their help. Looking forward to tomorrow!