[gambit-list] Using a function in a macro
benjohn at fysh.org
Sat Jun 18 17:17:15 EDT 2011
On 18 Jun 2011, at 17:13, Matthew Koichi Grimes wrote:
> You want:
> (define-macro (macro-inc x) (list 'inc x))
> (list 'inc x) evaluates at macro-expansion-time as (inc x), which at runtime evaluates to what you want.
> The code you wrote does work when entered in interactive mode (gsi); I seem to recall there being a thread in the past month or two about why that might be. I think the gist was that when running non-interactively, gsc does separate passes for macro-expansion, then evaluation. In the macro-expansion pass, it doesn't yet know about functions defined in that file, so calling those functions directly like you did results in an error. On the other hand, in interactive mode, each line gets its own macro-expansion and evaluation pass. So by the time we get to your (define two (macro-inc 1)) line, the macro-expansion pass recognizes 'inc', defined (in the evaluation pass) of an earlier line.
This makes sense, thank you. I think that means that I cannot easily do what I want to do.
Background: I have a library that defines several functions on intervals. If you perform these functions elementwise on a vector, then you can create many equivalent functions on n dimensional rectangles, and an n dimensional rectangle can be represented by a vector of intervals, etc.
I have a function that takes a function on scalars and turns it in to an elementwise function on vectors (which is useful for implementing vector addition, subtraction, and lots of other vector functions).
I would like to write a macro that will take the interval functions I have and build rectangle equivalents of them by slightly renaming the functions and binding these names to vectorised (elementwise) equivalents of the interval functions. Here's the macro I've written (that gives an error on usage indicating that string-find-replace isn't defined):
> ; Macro to define rectangle function from function in intervals by vectorising them.
> (define-macro (define-rectangle-function-from-interval-function func-name)
> ,(string->symbol (string-find-replace (symbol->string func-name) "interval" "rectangle"))
> ,(vector-make-elementwise-function func-name)
The function, string-find-replace is a function I've supplied in an imported file. It is in turn implemented in terms of srfi 13 functions. I'm using black hole.
So – I guess my real question is "how should I have a macro where I use functions I've written in the macro expansion?" :-)
benjohn at fysh.org - Twitter @benjohnbarnes - Skype benjohnbarnes - Mobile +44 (0) 7968 851 636
More information about the Gambit-list