Scheme /球拍中的静态变量?(Static variables in Scheme/Racket?)
在C中,你可以在一个方法中有一个静态变量,它可以记住以前调用该方法所设置的值。 我听说在Scheme中使用continuation可以找到相同的效果。 任何人都可以告诉我如何在不使用突变的情况下为Scheme中的函数创建静态变量的类似效果?
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?
最满意答案
这不需要延续。 这是一个典型的例子:
(define counter (let ([n 0]) (lambda () (set! n (add1 n)) n))) (list (counter) (counter) (counter))这里有一个明显的概括性来使它更有趣:
(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))这是第一个转换为JS的代码片段:
var counter = (function() { var n = 0; return (function() { n++; return n; }); })();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; }); })();更多推荐
发布评论