is it possible to have static variable inside a rebol function?

左心房为你撑大大i 提交于 2020-01-14 05:08:07

问题


This shows how to have a static variable inside an object or context: http://www.mail-archive.com/list@rebol.com/msg04764.html

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


回答1:


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



回答2:


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.



来源:https://stackoverflow.com/questions/2860925/is-it-possible-to-have-static-variable-inside-a-rebol-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!