Scheme /球拍中的静态变量?(Static variables in Scheme/Racket?)

编程入门 行业动态 更新时间:2024-10-28 19:31:13
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; }); })();

更多推荐

本文发布于:2023-07-15 22:03:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1119369.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:球拍   变量   静态   Scheme   variables

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!