Learning Scheme macros
Saturday, 20 September 2008
Thanks to Will Donnely’s Primer on Syntax-Rules, I finally got a headstart with Scheme macros.
What I find interesting about Scheme macros is that it uses the ellipsis (…) very intuitively when expanding macros.
For instance
[code lang="Scheme"]
;Next line for Guile only
(use-syntax (ice-9 syncase))
(define-syntax repeat
(syntax-rules ()
((repeat a1 ...)
'((lalala a1) ...))))
(display (repeat pork-chops roast-beef beetroot cheese))
[/code]
This macro matches for the pattern (repeat a1 a2 a3 etc …). The macro expansion is written this way: ((lalala a1) …), with the ellipsis written outside the brackets containing a1.
The end result is the list gets “unrolled”:
[code lang="Scheme"]
((lalala pork-chops)
(lalala roast-beef)
(lalala beetroot)
(lalala cheese))
[/code]
This style of notation makes for easy equivalents of Python’s “zip” function.
[code lang="Scheme"]
(define-syntax zip
(syntax-rules ()
((zip (a1 ...) (b1 ...))
'((a1 b1) ...))))
(write (zip (1 2 3 4 5 6) (a b c d e f))
; yields
; ((1 a) (2 b) (3 c) (4 d) (5 e) (6 f))
[/code]
You should follow me on twitter here