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

From: Matthias Felleisen (matthias at ccs.neu.edu)
Date: Sun Aug 16 12:22:03 EDT 2009

Use modules first to isolate globally mutable variables.

(module A scheme
  (define var 0)
  ... (set! var (+ var 1)) ...
  (provide var++ ... ) ;; but not var
  )

(module B scheme
  (require "A.ss")
  (var++)
  ...
  (var++)
  )






On Aug 16, 2009, at 11:29 AM, Amit Saha 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
>
> -- 
> Journal: http://amitksaha.wordpress.com
> µ-blog: http://twitter.com/amitsaha
> IRC: cornucopic on #scheme, #lisp, #math, #linux
> _________________________________________________
>  For list-related administrative tasks:
>  http://list.cs.brown.edu/mailman/listinfo/plt-scheme



Posted on the users mailing list.