[plt-scheme] The Scheme way of: Using 'global' variables ?

From: Anton Erdman (tentaclius at gmail.com)
Date: Sun Aug 16 11:54:16 EDT 2009

On Sun, 16 Aug 2009 20:59:28 +0530
Amit Saha <lists.amitsaha at gmail.com> wrote:

> Hello all,
> After C/Java/Python, I have been exclusively using Scheme
> (plt-scheme) for my day-day programming fun. Now, I have started
> facing situations where I simply am not sure the correct way to do
> something in Scheme. The latest case was something like this:
> I needed to use a 'global' identifier in my program, where I had some 
> procedures,  couple of which needed R/W access respectively and I
> wanted the value to persist for the lifetime of the program- just the
> way it happens for variables you define at the topmost level in say,
> C.
> So, what I did in scheme is- I just defined using (define var 0) and 
> used (set!..) to change value in one procedure and used the
> identifier name itself in some other procedure.
> For eg,
> <code>
> (define var 0)
> (define (proc1) (set! var (+ 1 var)))
> ; some other procs
> ; in
> ; between
> ;
> (define (proc2) (display var))
> </code>
> But, I think this is not the way this should be done in Scheme,
> because global variables is just calling for trouble in large
> programs. At the same time, I am not sure how to achieve the same
> thing in a better way, if there is one..
> PS: plt-scheme just has the necessary batteries to get started easily
> in Scheme :)
> Thanks a lot.
> Best Regards,
> Amit

I think, You can use modules or objects to isolate your global variable,
as it may be done in C/C++. PLT-scheme has rich set of functions
that work with namespaces. If it's what You have in mind.

If the variable needs to be really global, than, I think, you wr

Also You, probably, can use a function to isolate the variable, that
manipulates the value in different ways like this:

(define the-function
  (let ((the-variable 0))
    (lambda (operation . values)
      (case operation
        ((set) (set! the-variable (car values)))
        ((display) (display the-variable))))))

(the-function 'display) ;; => 0
(the-function 'set 11)
(the-function 'display) ;; => 11

I hope I understand you right way.

Posted on the users mailing list.