在 Perl 6 中描述斐波那契数列有多少种方法?

发布于 2024-09-28 12:03:27 字数 818 浏览 0 评论 0原文

我一直在研究在 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

风情万种。 2024-10-05 12:03:27

最短的好像是

my @fibs := ^2,*+*...*;

The shortest seems to be

my @fibs := ^2,*+*...*;
慕巷 2024-10-05 12:03:27

您可以使用黄金比例的魔力:设 φ=(sqrt(5)+1)/2,并定义 fib(n)=(φn+( 1-φ)n)/sqrt(5)。

您可以通过明显的方式将这样的函数转换为惰性列表: 在 Haskell 中,以下工作有效:

fibs=genfibs 0 where genfibs n=(round (fib n)):genfibs (n+1)

恐怕我的 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:

fibs=genfibs 0 where genfibs n=(round (fib n)):genfibs (n+1)

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文