[plt-scheme] #'(require help)
Laurent wrote:
> Hi all,
>
> I timidly require your help on a simple macro I've been trying to do for
> some time now.
>
> I usually prefer to do things myself, but I'm stuck.
>
> Here's the thing :
> I have an identifier and I want to generate an identifier based on it but
> with a different name.
> (in fact I have lots of identifiers)
>
> for example :
> (define-my-id trout)
> would generate the macro identifier my-id-trout that expands to, say,
> (display "trout").
> My concern is about using in the program an identifier that is not defined
> explicitly in the program file.
> This should be possible though, since this is partly what define-struct
> does, I suppose.
>
>
Maybe something like this is what you are after
#lang scheme
(define-syntax (define-my-id stx)
(syntax-case stx ()
[(_ id)
(with-syntax ([my-id (datum->syntax
#'id
(string->symbol
(string-append "my-id-"
(symbol->string
(syntax->datum #'id))))
#'id)])
#'(define-syntax-rule (my-id) (display 'id)))]))
(define-my-id foo)
(my-id-foo)
;; end
In general if you want to create new identifiers you should use
syntax-case and with-syntax. with-syntax takes some syntax and binds it
to an identifier that can be used in a template and you are free to
generate the syntax that it binds. define-syntax-rule is just a
shorthand for (define-syntax foo (syntax-rules ...)).
> With eval and quasi-quoting I can easily generate an approximation with a
> lambda'd form but Scheme won't let me use identifiers that are not
> explicitly defined (it works in the REPL though):
> (define (define-my-id id)
> (eval `(define ,(string->symbol (string-append "my-id-" (symbol->string
> id)))
> (lambda () (display ,(symbol->string id))))))
>
> I also know that syntax-id-rules can generate expanding identifiers, but I
> can't use string-append et al in macros to generate a new id...
>
>
If you want to use the result of the above macro as 'my-id-foo' instead
of '(my-id-foo)' then you can use syntax-id-rules, but using eval is
usually not the right way to generate new identifiers.
> Also, where can I find some simple macro samples, other than in the guide ?
>
>
I guess you can look at code on planet or in the collects directory of
the PLT tree, but I'm beginning to think a more expansive explanation
section of the docs would be useful. Something like extremely detailed
comments about "real code".