Lua - 将coroutine递归重写为尾调用递归

Lor*_*rai 3 recursion lua tail-recursion coroutine

我必须编写一个可以遍历嵌套表的迭代器.我写了一个使用coroutine.

它创建了一个(路径,值)对的数组,例如{{key1, key2, key3}, value}意味着要让value你去做nested_table[key1][key2][key3].

当我写find(),findall(),in()轻松,生活是光明的.

function table.extend(tbl, new_value)
  local tbl = {table.unpack(tbl)}
  table.insert(tbl, new_value)
  return tbl
end

function iterate(tbl, parent)
  local parent = parent or {}
  if (type(tbl)=="table") then
    for key, value in pairs(tbl) do
      iterate(value, table.extend(parent, key))
    end
  end
  coroutine.yield(parent, tbl)
end

function traverse(root)
   return coroutine.wrap(iterate), root
end
Run Code Online (Sandbox Code Playgroud)

然后我意识到我必须使用的Lua环境已coroutine被列入黑名单.我们不能使用它.所以我尝试没有相同的功能coroutine.

-- testdata

local pool = {}
test = {
  ['a'] = 1,
  ['b'] = {
    ['c'] = {2, 3},
    ['d'] = 'e'
  }
}

-- tree traversal

function table.extend(tbl, element)
  local copy = {table.unpack(tbl)}
  table.insert(copy, element)
  return copy
end

local function flatten(value, path)
  path = path or {'root'}
  pool[path] = value -- this is the 'yield'
  if type(value) == 'table' then
    for k,v in pairs(value) do
      flatten(v, table.extend(path, k))
    end
  end
end

-- testing the traversal function

flatten(test)

for k, v in pairs(pool) do
  if type(v) == 'table' then v = '[table]' end
  print(table.concat(k, ' / ')..' -> '..v)
end
Run Code Online (Sandbox Code Playgroud)

此代码返回我需要的内容:

root -> [table]
root / b / c / 1 -> 2
root / b -> [table]
root / a -> 1
root / b / d -> e
root / b / c / 2 -> 3
root / b / c -> [table]
Run Code Online (Sandbox Code Playgroud)

但我仍然有一个问题:我不能使用全局变量pool,这个代码被称为并行.我不能return flatten(...)从一个for循环中做正确的尾调用递归(),因为它只返回一次.

所以我的问题是:如何将此函数打包成可以并行调用的函数?换句话说:我可以实现'yield'部分对返回值的作用,而不是将结果传递给全局变量吗?

我试图让它成为一个对象,遵循这里的模式,但我无法让它工作.

Ego*_*off 6

你可以pool变量local:

test = {
   ['a'] = 1,
   ['b'] = {
      ['c'] = {2, 3},
      ['d'] = 'e'
   }
}

-- tree traversal

function table.extend(tbl, element)
   local copy = {table.unpack(tbl)}
   table.insert(copy, element)
   return copy
end

local function flatten(value, path, pool)    -- third argument is the pool
   path = path or {'root'}
   pool = pool or {}                                    -- initialize pool
   pool[path] = value
   if type(value) == 'table' then
      for k,v in pairs(value) do
         flatten(v, table.extend(path, k), pool)  -- use pool in recursion
      end
   end
   return pool                           -- return pool as function result
end

-- testing the traversal function

local pool = flatten(test)

for k, v in pairs(pool) do
   if type(v) == 'table' then v = '[table]' end
   print(table.concat(k, ' / ')..' -> '..v)
end
Run Code Online (Sandbox Code Playgroud)