Posts tagged macros
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.
In my previous post, I wrote about a nuance with syntax/loc
, using the example of a macro that both define
s and provide
s 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.
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?
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.
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.
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.
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.