[plt-scheme] Defining global functions with shared state?
On Tue, Mar 17, 2009 at 3:32 PM, Jeff de Vries <jdevries at pfrog.com> 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?
> Thanks,
> Jeff de Vries
>
This may also be deemed somewhat clunky...
(define-syntax (define-with-state stx)
(syntax-case stx ()
[(_ (state-name state-gen) (fname fbody) ...)
(let ((s (gensym)))
#`(begin
(define #,s state-gen)
(define fname (let ((state-name #,s)) fbody))
...))]))
(define-with-state (state (cons 1 2))
(foo (lambda () (car state)))
(bar (lambda () (cdr state))))
Anthony