Posts tagged macros

Keyword structs, revisited

:: Racket, macros, software

This revises my Keyword structs post to fix some mistakes, discuss the struct* match pattern, and rewrite the macro to use syntax-parse and support default arguments.

A good rule of thumb in Racket is to use a struct instead of list when you’re juggling more than two or three items.

Using syntax/loc and unit test macros

:: Racket, racket-cookbook, macros

In my previous post, I wrote about a nuance with syntax/loc, using the example of a macro that both defines and provides a function. But why don’t I back up, and look at a simpler example of why you’d want to use syntax/loc. The example is a simple macro you might often find yourself wanting, to reduce the tedium of writing unit test cases.

Using syntax/loc

:: Racket, macros

There’s a nuance to syntax/loc. The documentation says, emphasis mine:

Like syntax, except that the immediate resulting syntax object takes its source-location information from the result of stx-expr (which must produce a syntax object), unless the template is just a pattern variable, or both the source and position of stx-expr are #f.

What does “immediate” mean here?

A case with fall-through

:: Racket, macros

Jay McCarthy posted about a macro to do a C-style case, where clauses fall through to the next unless you use a break. His post is a great look at Racket macrology. Jay’s implementation is elegant. If you haven’t yet, go read it.

The ~> Threading Macro

:: Racket, Clojure, macros

Although I prefer Racket, there are a few idioms from Clojure I like. I’m particularly infatuated with the threading macros, -> and ->>.

I was surprised how little documentation I could find for these. So although I’m writing this for Racketeers, it’s possible a few Clojure folks might find it interesting, too.

Keyword structs

:: Racket, macros, software

NOTE: You may want to skip to Keyword structs, revisited.

A good rule of thumb in Racket is to use a struct instead of list when you’re juggling more than two or three items.

Fear of Macros

:: macros, Racket, software

I learned Racket after 25 years of mostly using C and C++.

Some psychic whiplash resulted.

“All the parentheses” was actually not a big deal. Instead, the first mind warp was functional programming. Before long I wrapped my brain around it, and went on to become comfortable and effective with many other aspects and features of Racket.

But two final frontiers remained: Macros and continuations.