[plt-scheme] Defining global functions with shared state?
On Mar 17, 2009, at 1:25 PM, Thomas Chust wrote:
> 2009/3/17 Jeff de Vries <jdevries at pfrog.com>:
>> 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)))
>> [...]
>
> you could let your macro expand into a define-values form that looks
> like this:
>
> (define-values (foo bar)
> (let ([state (create-common-state)])
> (values
> (lambda (x) (use-common-state-one-way x state))
> (lambda (x) (use-common-state-another-way x state)))))
Yes, that's what I was looking for. Short, sweet, easy to understand,
and does exactly what I wanted.
Regarding some of the other comments:
The original was "clunky" in the sense that it first created the
global names (initially set to null), and then went back and set the
values in another pass. It was also not very clean if the create-
common-state function blew up; in the original the global names are
defined first, so if create-common-state blows up, those names are
left hanging around. The define-values approach gets around that
issue, in that if create-common-state blows up, nothing gets defined.
The other suggestions basically create a global gensym'd name for the
common-state. But I really don't want these common-state objects
polluting the global namespace, since they really don't need to.
Again, the define-values approach does what I want.
Thanks for all the comments and suggestions!
Jeff
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.racket-lang.org/users/archive/attachments/20090317/dad5b849/attachment.html>