在 Perl 6 中描述斐波那契数列有多少种方法?
我一直在研究在 Perl 6 中构造惰性列表的各种方法,并且我想收集所有描述斐波那契数列的简洁方法。
我将从 masak 日记中的三个开始:
my @fibs := (0, 1, -> $a, $b { $a + $b } ... *);
my @fibs := (0, 1, { $^a + $^b } ... *);
my @fibs := (0, 1, *+* ... *);
我在想类似的事情这也可以,但我认为我的语法错误:
my @fibs := (0, 1, (@fibs Z+ @fibs[1..*]));
有一些东西很急切(切片?)并导致 Rakudo 进入无限循环。这是 Haskell 定义的翻译:
fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
更新:
看起来 zipWith
示例的问题是 @fibs[1..*]
切片。如果 tail
定义为 sub tail (@x) {my $i = 1; {@x[$i++]}...*}
然后就可以正常工作了。我很想知道为什么切片对于熟悉 Rakudo 内部结构的人来说并不懒惰。
另一个不错的是:
my @fibs := (0, [\+] 1, @fibs);
I've been looking at the various ways of constructing lazy lists in Perl 6 and I would like to collect all of the concise ways of describing the Fibonacci sequence.
I will start this off with the three from masak's journal:
my @fibs := (0, 1, -> $a, $b { $a + $b } ... *);
my @fibs := (0, 1, { $^a + $^b } ... *);
my @fibs := (0, 1, *+* ... *);
I was thinking something like this would also work, but I think I have the syntax wrong:
my @fibs := (0, 1, (@fibs Z+ @fibs[1..*]));
Something there is eager (the slice?) and causes Rakudo to enter an infinite loop. It's a translation of the Haskell definition:
fibs = 0 : 1 : zipWith (+) fibs (tail fibs)
Update:
Seems like the problem with the zipWith
example is the @fibs[1..*]
slice. if tail
is defined as sub tail (@x) {my $i = 1; {@x[$i++]}...*}
then it works properly. I would be interested to know why the slice isn't lazy from anyone familiar with Rakudo's internals.
Another nice one is:
my @fibs := (0, [\+] 1, @fibs);
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最短的好像是
The shortest seems to be
您可以使用黄金比例的魔力:设 φ=(sqrt(5)+1)/2,并定义 fib(n)=(φn+( 1-φ)n)/sqrt(5)。
您可以通过明显的方式将这样的函数转换为惰性列表: 在 Haskell 中,以下工作有效:
恐怕我的 Perl 6 知识无法翻译这个,抱歉!任何编辑此答案并在代码中进行编辑的人都将赢得我的感激。
一个更具测试性的问题是列出生成汉明数惰性列表的方法。
You can use the magic of the golden ratio: let φ=(sqrt(5)+1)/2, and define fib(n)=(φn+(1-φ)n)/sqrt(5).
You can convert such a function into a lazy list in the obvious way: In Haskell the following works:
I'm afraid my Perl 6 knowledge isn't up to translating this, sorry! Anyone who edits this answer to edit in the codes will earn my gratitude.
A more testing question would be to list ways of generating the lazy list of Hamming numbers.