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

From: Matthias Felleisen (matthias at ccs.neu.edu)
Date: Sun Aug 16 15:23:57 EDT 2009

If you like this:

On Aug 16, 2009, at 3:03 PM, Amit Saha wrote:

>> (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


use classes instead:

#lang scheme

(define the-function%
   (class object%
     (init-field var)
     (define/public (var++) (set! var (+ var 1)))
     (define/public (display) (printf "~s\n" var))
     (super-new)))

(define the-function (new the-function% [var 0]))
(send the-function display) ;; => 0
(send the-function var++)
(send the-function display) ;; => 11


It really scales. -- Matthias



Posted on the users mailing list.