[plt-scheme] macros that expand into top-level definitions with computed names

From: Matthias Felleisen (matthias at ccs.neu.edu)
Date: Wed Aug 12 12:25:25 EDT 2009

On Aug 12, 2009, at 11:26 AM, Lee Spector wrote:

>
> In fact I DO know partial-name at compile time, or at least at what  
> should be compile time for the code that will call the resulting  
> functions. That is, I'm not going to be doing things like taking  
> input from the user that gets turned into function names. But I  
> want to do some computation to produce the function names and  
> definition bodies since these will be combinatorial products of  
> lists of symbols. Is there a way to do this either using PLT macros  
> or module instantiation phases?

Here is a macro that computes with partial name? Is this good enough?


#lang scheme/load

(module c scheme
   (define partial-name "yours")
   (provide partial-name))


(module a scheme
   (require (for-template 'c) (for-syntax 'c))

   (define-syntax (def stx)
     (syntax-case stx ()
       [(_ f x body ...)
        (let* ([f:sym (syntax-e (syntax f))]
               [my-f:str (string-append "my-" partial-name (number- 
 >string (string-length partial-name)) (symbol->string f:sym))]
               [my-f:sym (string->symbol my-f:str)]
               [my-f:id (datum->syntax stx my-f:sym)])
          (printf "~a\n" my-f:sym)
          #`(define #,my-f:id (lambda (x) body ...)))]))

   (provide def))

(module b scheme
   (require 'a)

   (def f x (sqrt x))

   (printf "~a\n" (my-yours5f 4))

   (def yours x (sqrt x))

   (printf "~a\n" (my-yours5yours 4)))

(require 'b)


Posted on the users mailing list.