开发者

How many ways are there to describe the Fibonacci sequence in Perl 6?

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 fib开发者_运维技巧s)

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);


The shortest seems to be

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜