[plt-scheme] Defining global functions with shared state?

From: Ryan Culpepper (ryanc at ccs.neu.edu)
Date: Tue Mar 17 16:57:32 EDT 2009

On Mar 17, 2009, at 3:32 PM, Jeff de Vries wrote:

> I'm trying to create a macro that creates a set of global function  
> definitions where those functions share some common state.   
> Basically, the intent is something like the following:
>
> ;;; doesn't work, creates local definitions instead of global ones
> (let ((state (create-common-state)))
>   (define (foo x) (use-common-state-one-way x state))
>   (define (bar x) (use-common-state-another-way x state)))
>
> I ended up making a macro that generates the following:
>
> (define foo null)
> (define bar null)
> (let ((state (create-common-state)))
>   (set! foo (lambda (x) (use-common-state-one-way x state)))
>   (set! bar (lambda (x) (use-common-state-another-way x state))))
>
> That works, but it seems a little clunky.  Is there a better way?

Essentially, you want a splicing version of 'let'. It's a "splicing"  
binding form in the sense that the definitions inside the local  
binding should be visible outside of it. The 'scheme/splicing' module  
has several splicing forms, but no 'splicing-let'. Here's one way to  
write it:

#lang scheme
(require (for-syntax scheme/base)
          scheme/splicing)

(define-syntax (splicing-let stx)
   (syntax-case stx ()
     [(splicing-let ([x rhs] ...) . b)
      (with-syntax ([(tmp ...) (generate-temporaries #'(x ...))])
        #'(begin
            (define tmp rhs) ...
            (splicing-let-syntax ([x (make-rename-transformer #'tmp)]
                                  ...)
              . b)))]))

Perhaps this should go into 'scheme/splicing'?

Ryan

> _________________________________________________
>  For list-related administrative tasks:
>  http://list.cs.brown.edu/mailman/listinfo/plt-scheme

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.racket-lang.org/users/archive/attachments/20090317/dee6fb67/attachment.html>

Posted on the users mailing list.