我在Ruby中關閉了閉包,並遇到了以下我無法理解的情況。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"]
...
任何人都可以解釋到底發生了什麼?
這是完美的。非常感謝你所有的努力:)。 – Reck