Hello,
By default, I try to write code using basic Scheme idioms. But if I'm
rewriting code from languages like C, C++, Ruby, etc, which have nice
shorthand syntax for array element access, structure access, and method
calling, it really makes me wanna cook something up on the Scheme side
to achieve similar concision.
One approach I've messed around with and have liked is as follows.
Here's an 'is-vector' macro:
(define-syntax is-vector
(lambda (stx)
(syntax-case stx ()
((is-vector name)
(with-syntax ( (name.ref (gen-id #'name #'name ".ref"))
(name.set! (gen-id #'name #'name ".set!"))
(name.length (gen-id #'name #'name ".length")) )
#'(begin
(define (name.ref i) (vector-ref name i))
(define (name.set! i val) (vector-set! name i val))
(define (name.length) (vector-length name))))))))
'gen-id' is from TSPL:
(define (gen-id template-id . args)
(datum->syntax template-id
(string->symbol
(apply string-append
(map (lambda (x)
(if (string? x)
x
(symbol->string (syntax->datum x))))
args)))))
Example:
(define v '#(a b c d e))
(is-vector v)
(v.ref 0)
(v.set! 0 'x)
(v.length)
I've used similar macros for getting at record elements.
Perhaps argument-less "methods" like .length should just be identifier
syntax.
Anyways, just wondering, do any of y'all use similar techniques? I
wouldn't mind reusing an existing library for stuff like this.
Ed