rebol 函数中是否可以有静态变量?

发布于 2024-09-01 16:22:15 字数 314 浏览 1 评论 0原文

这展示了如何在对象或上下文中拥有静态变量: http://www.mail-archive.com/[email protected]/msg04764.html

但是范围对于某些需求来说太大了,是否可以在对象函数内部有一个静态变量?

This shows how to have a static variable inside an object or context:
http://www.mail-archive.com/[email protected]/msg04764.html

But the scope is too large for some needs, is it possible to have a static variable inside an object function ?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

猫九 2024-09-08 16:22:15

或者您可以使用FUNCTION/WITH。这使得函数生成器采用第三个参数,该参数定义了一个用作“self”的持久对象:

accumulate: function/with [value /reset] [
    accumulator: either reset [
        value
    ] [
        accumulator + value
    ]
] [
    accumulator: 0
]

要使用它:

>> accumulate 10
== 10

>> accumulate 20
== 30

>> accumulate/reset 0
== 0

>> accumulate 3
== 3

>> accumulate 4
== 7

您可能还需要查看我的 FUNCS 函数

Or you can use FUNCTION/WITH. This makes the function generator take a third parameter, which defines a persistent object that is used as the "self":

accumulate: function/with [value /reset] [
    accumulator: either reset [
        value
    ] [
        accumulator + value
    ]
] [
    accumulator: 0
]

To use it:

>> accumulate 10
== 10

>> accumulate 20
== 30

>> accumulate/reset 0
== 0

>> accumulate 3
== 3

>> accumulate 4
== 7

You may also want to look at my FUNCS function.

来世叙缘 2024-09-08 16:22:15

在 Rebol 3 中,使用闭包(或 CLOS)而不是函数(或 FUNC)。

在 Rebol 2 中,通过包含静态值的块来伪造它,例如:

f: func [
   /local sb
][
     ;; define and initialise the static block
 sb: [] if 0 = length? sb [append sb 0]

     ;; demonstate its value persists across calls
 sb/1: sb/1 + 1
 print sb
 ]

    ;; sample code to demonstrate function
 loop 5 [f]
 == 1
 == 2
 == 3
 == 4
 == 5

In Rebol 3, use a closure (or CLOS) rather than a function (or FUNC).

In Rebol 2, fake it by having a block that contains your static values, eg :

f: func [
   /local sb
][
     ;; define and initialise the static block
 sb: [] if 0 = length? sb [append sb 0]

     ;; demonstate its value persists across calls
 sb/1: sb/1 + 1
 print sb
 ]

    ;; sample code to demonstrate function
 loop 5 [f]
 == 1
 == 2
 == 3
 == 4
 == 5
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文