我正在复习课堂上的幻灯片。代码应该打印“早期工作”一次,然后打印“后期工作”两次(您可以设置后期工作的重复次数)。但我想知道为什么这段代码不能工作,以及如何修改代码?因为现在代码将生成“后期工作”的无限循环,而不是2(应该是)
require 'continuation'
def work
p "early work"
here = callcc {|here| here}
p "later work"
return here
end
def rework(k)
entry = work
k.times do |i|
entry.call(entry)
end
end
rework(2)发布于 2017-10-05 11:22:34
代码无法工作,因为k.times中的循环计数器被卡住了。每次对entry.call(entry)的调用都会将程序倒回到callcc返回时。所以callcc再次返回,后面的工作再次发生,work再次返回,k.times再次启动。当k.times启动时,它将其循环计数器重置为零。无限循环是因为循环计数器始终为零。
要修复程序,我们必须继续循环,而不是重新启动它。最好的解决方法是使用纤程,但首先,我尝试使用延续。下面是在我的机器上运行的版本:
require 'continuation'
def work
p "early work"
here = callcc {|here| here}
p "later work"
return here
end
class Integer
def my_times
i = 0
while i < self
yield i
i += 1
end
end
end
def rework(k)
entry = nil
k.my_times do |i|
if i == 0
entry = work
else
entry.call(entry)
end
end
end
rework(2)我通过在循环内调用work来修复控制流。当work再次返回时,我不会重置循环计数器。
我也定义了我自己的Integer#my_times,并且不使用Ruby的Integer#times。如果我把代码从k.my_times改回k.times,循环计数器又被卡住了。这暴露了Ruby中延续对象的一个问题。
当延续倒带程序时,它可能会倒带或保留局部变量的值。我的程序假设entry.call保留循环计数器。Matz的Ruby实现在Integer#my_times中保留了循环计数器,但在Integer#times中倒带了循环计数器。这是我的程序不能使用Integer#times的唯一原因。
MRI似乎在C代码中倒带局部变量(如Integer#times),但在Ruby代码中保留局部变量(如Integer#my_times)。这使得循环计数器和其他本地变量变得一团糟。Ruby没有解决这个问题,但对callcc提出了警告。鲁比说,warning: callcc is obsolete; use Fiber instead。
下面是使用纤程的程序:
def work
p "early work"
here = Fiber.new do
while true
p "later work"
Fiber.yield
end
end
here.resume
return here
end
def rework(k)
entry = nil
k.times do |i|
if i == 0
entry = work
else
entry.resume
end
end
end
rework(2)https://stackoverflow.com/questions/40709030
复制相似问题