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?
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;
});
})();
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With