函数中局部变量的值似乎未被释放 post Red/Rebol 语言中的函数调用

Value of local variables in a function seems not be released post function calling in Red/Rebol language

我构建了一个名为 find-all 的函数,通过“递归”查找系列中给定项目的所有索引。 find-all 的第一次调用给出了正确的输出。但是从第二次调用开始,所有输出都附加在一起。

find-all: function [series found][
result: [] 
  either any [empty? series none? s-found: find series found]
     [result]
     [append result index? s-found
      find-all next s-found found]
]

;; test:
probe find-all "abcbd" "b"   ;; output [2 4] as expected
probe find-all [1 2 3 2 1] 2  ;; output [2 4 2 4]

既然用function创建的函数内部的变量是局部的,为什么在后面的函数调用中变量result的值还在,导致第二个的result find-all 的调用不是以 [] 开头? 实现此功能的正确递归方法是什么?

如果您在进行这两个调用后检查 find-all,答案就很明显了:

>> ?? find-all
find-all: func [series found /local result s-found][
    result: [2 4 2 4] 
    either any [empty? series none? s-found: find series found] 
    [result] 
    [append result index? s-found 
        find-all next s-found found
    ]
]

result是一个,它的数据缓冲区存储在堆上。数据在调用之间保存并累积,因为您不使用 copy 重新创建它 - result 是函数上下文的本地与此无关。

感谢@9214的帮助,特别是关于indirect value的描述。我给出这样的解决方案:

find-all: function [series found][
  either any [empty? series none? s-found: find series found]
     [[]]
     [append
        reduce [index? s-found]
        find-all next s-found found
    ]
]

;; test:
probe find-all "abcbd" "b"   ;; output [2 4] as expected
probe find-all [1 2 3 2 1] 2  ;; output [2 4] as expected