gpt4 book ai didi

ruby - callcc -- 当前继续调用

转载 作者:太空宇宙 更新时间:2023-11-03 18:26:13 26 4
gpt4 key购买 nike

我开始接触 Ruby 并遇到了一个以前从未见过的函数 -- callcc
我已经了解了它的用途的一些一般概念,但是当我尝试编写一个示例时却得到了意想不到的结果。

require 'continuation'
def callcc_func
i = 0
while true
c = nil
callcc {|x| c = x}
i += 1
puts i
return c if (i % 3) == 0
end
end

c = callcc_func()
puts
callcc_func.call

结果是死循环。为什么?
我预计它会是:

# for `c = callcc_func()` line
1
2
3

# callcc_func.call
4
5
6
#end here because of `return c if (i % 3) == 0`

附言
对不起我的英语,谢谢。

最佳答案

这个答案有点晚了,但也许有人会感兴趣。

您只需将代码的最后一行更改为:

c.call

此功能的应用之一是制作发电机。这是示例随机数生成器(取自《数值食谱》一书的常量):

def randomLCG(a,m,c,seed)
initialized = false
while true
callcc {|x| $cc = x}
if not initialized
initialized = true
return
end
seed = (a*seed + c) % m;
return seed
end
end

和用法:

> randomLCG( 1664525, 2147483647 , 1013904223, 107 )
=> nil
> $cc.call
=> 1192008398
> $cc.call
=> 2079128816
> $cc.call
=> 667419302

在 Python 中,我们可能会使用关键字 yield 来实现相同的目标(请注意在 Ruby 中关键字 yield 做不同的事情):

def randLCG (a , m , c , seed):
while True:
seed = ( a∗seed + c ) % m
yield seed

用法:

>>> random = randLCG ( 1664525 , 2147483647 , 1013904223, 107 ) 
>>> random
<generator object randLCG at 0x7fdc790f70a0>
>>> random.next()
1192008398
>>> random.next()
2079128816
>>> random.next()
667419302

Ofc 在 Ruby ofc 中,你可以使用闭包来解决这个问题,这样你的程序就会更短:

require 'continuation'

def rand(a, m, c, seed)
return lambda{ seed = (a*seed + c) % m; return seed }
end

c = rand( 1664525, 2147483647 , 1013904223, 107 )
c.call
c.call

我想到的第二种用法是实现 mutual recursions .

关于ruby - callcc -- 当前继续调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10615536/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com