我在 Ruby 中搞乱了闭包,遇到了以下我无法理解的场景。
def find_child_nodes(node)
left_node_name = "#{node}A"
right_node_name = "#{node}B"
[left_node_name, right_node_name]
end
# use a stack of closures (lambdas) to try to perform a breadth-first search
actions = []
actions << lambda { {:parent_nodes => ['A'], :child_nodes => find_child_nodes('A') } }
while !actions.empty?
result = actions.shift.call
puts result[:parent_nodes].to_s
result[:child_nodes].each do |child_node|
parent_nodes = result[:parent_nodes] + [child_node]
actions << lambda { {:parent_nodes => parent_nodes, :child_nodes => find_child_nodes(child_node) } }
end
end
上面的代码返回以下广度优先搜索输出:
["A"]
["A", "AA"]
["A", "AB"]
["A", "AA", "AAA"]
["A", "AA", "AAB"]
["A", "AB", "ABA"]
["A", "AB", "ABB"]
["A", "AA", "AAA", "AAAA"]
...
到现在为止还挺好。但是现在如果我改变这两行
parent_nodes = result[:parent_nodes] + [child_node]
actions << lambda { {:parent_nodes => parent_nodes, :child_nodes => find_child_nodes(child_node) } }
到这一行
actions << lambda { {:parent_nodes => result[:parent_nodes] + [child_node], :child_nodes => find_child_nodes(child_node) } }
我的搜索不再是广度优先。相反,我现在得到
["A"]
["A", "AA"]
["A", "AA", "AB"]
["A", "AA", "AB", "AAA"]
["A", "AA", "AB", "AAA", "AAB"]
...
谁能解释一下这里发生了什么?