【问题标题】:Value of local variables in a function seems not be released post function calling in Red/Rebol language函数中局部变量的值似乎没有在 Red/Rebol 语言中调用函数后释放
【发布时间】:2021-04-02 02:39:05
【问题描述】:

我构造了一个名为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的值还在,导致第二次调用find-allresult没有开始[]? 实现此功能的正确递归方式是什么?

【问题讨论】:

    标签: rebol red rebol3 rebol2


    【解决方案1】:

    如果您在拨打这两个电话后检查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 是一个indirect value,它的数据缓冲区存储在堆上。数据在调用之间被保留并累积,因为您没有使用 copy 重新创建它 — result 是函数上下文的本地与此无关。

    【讨论】:

      【解决方案2】:

      感谢@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
      

      【讨论】:

        猜你喜欢
        • 2023-04-07
        • 2019-04-15
        • 1970-01-01
        • 1970-01-01
        • 2010-09-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-06-04
        相关资源
        最近更新 更多