Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static variables in Scheme/Racket?

In C, you can have a static variable within a method, which can remember values to which it was set by previous calls of the method. I heard that the same effect can be found by using continuations within Scheme. Can anyone show me how to create the similar effect of a static variable for a function in Scheme without using mutation?

like image 551
djhaskin987 Avatar asked Dec 27 '22 09:12

djhaskin987


2 Answers

You don't need continuations for that. Here's a classic example:

(define counter
  (let ([n 0])
    (lambda ()
      (set! n (add1 n))
      n)))
(list (counter) (counter) (counter))

And here's an obvious generalization to make it more interesting:

(define (make-counter n)
  (lambda ()
    (set! n (add1 n))
    n))
(define a (make-counter 0))
(define b (make-counter 10))
(list (a) (a) (a) (b) (b) (a) (a))

And here's the first piece of code translated to JS:

var counter = (function() {
                 var n = 0;
                 return (function() {
                           n++;
                           return n;
                         });
               })();
like image 160
Eli Barzilay Avatar answered Jan 06 '23 17:01

Eli Barzilay


You can close values in Scheme (or any language with a decent lambda construct), so closures give you a good way to have "static variables".

(and if you want to mutate these closed values, you could put them in a container)

like image 30
Basile Starynkevitch Avatar answered Jan 06 '23 17:01

Basile Starynkevitch