[racket] Macros: dealing with optional elements

From: J. Ian Johnson (ianj at ccs.neu.edu)
Date: Wed Sep 25 06:51:50 EDT 2013

This is such a common pattern that there is support for it with a feature called syntax templates, in syntax/parse/experimental/template. You would use (?? super) to add super only if it's given, and nothing otherwise.
-Ian
----- Original Message -----
From: Laurent <laurent.orseau at gmail.com>
To: Konrad Hinsen <konrad.hinsen at fastmail.net>
Cc: users <users at racket-lang.org>
Sent: Wed, 25 Sep 2013 06:17:30 -0400 (EDT)
Subject: Re: [racket] Macros: dealing with optional elements

On Wed, Sep 25, 2013 at 11:31 AM, Konrad Hinsen
<konrad.hinsen at fastmail.net>wrote:

>
>    (define-syntax (foo stx)
>      (syntax-parse stx
>                    [(_ id:id (~optional super:id) (field:id ...))
>                     (if (attribute super)
>                         #'(struct id super (field ...))
>                         #'(struct id (field ...)))]))



Unsyntax-splicing to the rescue!

#lang racket
(require (for-syntax syntax/parse))

(define-syntax (foo stx)
  (syntax-parse stx
    [(_ id:id (~optional super:id) (field:id ...))
     #`(struct id
         #,@(if (attribute super)
                (list #'super)
                '())
         (field ...))
     ]))

(struct A (a))

(foo B (b))
(foo C A (c))

(A 1)
(B 2)
(C 3 4)


Laurent


Posted on the users mailing list.