[plt-scheme] Generating top-level definitions from inner syntax

From: Bruce Hauman (bhauman at sol.cs.wcu.edu)
Date: Thu Oct 9 14:26:13 EDT 2003

On Thu, 9 Oct 2003, Lauri Alanko wrote:

>   For list-related administrative tasks:
>   http://list.cs.brown.edu/mailman/listinfo/plt-scheme
>
> Here's something that would be very handy:
>
> (module foo mzscheme
>   ...
>   (define (decimal? str)
>     (pair? (match-optimized "-?[0-9]+" str)))
>   ...
> )
>
> Would get transformed to:
>
> (module foo mzscheme
>   ...
>   (define g125235 (regexp "-?[0-9]+"))
>   (define (decimal? str)
>     (pair? (regexp-match g125235 str)))
>   ...
> )
>
> That is, I'd like an inner syntax to somehow introduce a top-level
> definition to hoist a complex computation so that it only gets computed
> once. Of course one can always use memoization, but it'd be nice to be
> able to do this right.

If I am not mistaken it looks like capturing the complex computation
in a local closure would work for your example, because it does not seem
to allow for module scope use of the defined value.

So, is the following a good idea?

(define-syntax lambda-capture
  (lambda (stx)
    (let ((capture-list '()))
      (letrec ((find-captures
                (lambda (stx)
                  (syntax-case stx (capture)
                    ((capture exp)
                     (let ((temp (gensym 'capt)))
                       (set! capture-list
                            (cons #`(#,temp exp)
                             capture-list))
                       #`#,temp))
                    ((car-part . cdr-part)
                     #`#,(cons (find-captures (syntax car-part))
                               (find-captures (syntax cdr-part))))
                    (other
                     (syntax other))))))
        (syntax-case (find-captures stx) ()
          ((_ arg rest ...)
           #`(let #,capture-list
               (lambda arg
                   rest ...))))))))

(define check-something
  (lambda-capture (x)
     (pregexp-match (capture (pregexp "hello")) x)))

Where the lambda-capture expression expands to:

(let ((capt1478 (pregexp "hello")))
    (lambda (x) (pregexp-match capt1478 x)))


Bruce




Posted on the users mailing list.