[racket] syntax-id-rules

From: Harry Spier (vasishtha.spier at gmail.com)
Date: Thu Dec 8 12:48:29 EST 2011

Dear list members,

As an exercise to learn Racket macros I'm setting up macros as getters
and setters on multi-dimensional arrays where the array reference is
array[dimension1 dimension2 ...]
This is useful for my application but the main reason is to learn macros.

I'm able to set up getter and setter macros using syntax-rules as follows:
--------------------------------------------------
(define v1 (vector
            (vector (vector 1 2 3)
                    (vector 11 22 33)
                    (vector 111 222 333))
            (vector (vector 1 2 3)
                    (vector 11 22 33)
                    (vector 111 222 333))))


(define-syntax get-array-element
  (syntax-rules ()
    [(get-array-element v[d1]) (vector-ref v d1)]
    [(get-array-element v[d1  d2 ...] ) (get-array-element (vector-ref
v d1)[d2 ...] )]))

(define-syntax set-array-element!
  (syntax-rules ()
    [(set-array-element! v[d1] exp) (vector-set! v d1 exp)]
    [(set-array-element! v[d1 d2 ...] exp) (set-array-element!
(vector-ref v d1)[d2 ...]exp)]))

(get-array-element  v1[1 1 1])
(set-array-element! v1[1 1 0] 999999)

-------------------------------------------------
which works just fine but when I try the following using syntax-id-rules:

(define-syntax array-element
  (syntax-id-rules (get set!)
    [(get array-element  v[d1]) (vector-ref v d1)]
    [(get array-element  v[d1  d2 ...] ) (get array-element
(vector-ref v d1)[d2 ...] )]
    [(set! array-element  v[d1] exp) (vector-set! v d1 exp)]
    [(set! array-element  v[d1 d2 ...] exp) (set! array-element
(vector-ref v d1)[d2 ...]exp)]))


(get array-element  v1[1 1 1])
(set! array-element v1[1 1 0] 999999)
-------------------------------------------------------
I get the error for (get array-element v1[1 1 1]  "expand: unbound
identifier in module in: get"
and for (set! array-element v1[1 1 1] I get the error of: "set!: bad
syntax (has 4 parts after keyword) in: (set! array-element v1 (1 1 0)
999999)"

Using syntax-id-rules is there a way to write my array-element macro so that :
(get array-element  v1[1 1 1])
(set! array-element v1[1 1 0] 999999)
work correctly without the "get" and "set!" identifiers giving me errors.

I know I can write get and set! macros using syntax-rules to do this,
but I'm doing this mainly as a learning exercise about
syntax-id-rules.

Many thanks,
Harry Spier


Posted on the users mailing list.