views:

491

answers:

3

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

Don't forget the obvious look-up table.

Anonymous
How can this be generated lazily? It seems to be a question-begging answer.
Charles Stewart
A: 
Charles Stewart
Sorry to be pedantic, but for clarification: the golder ratio is 0.5*(sqrt(5)+1) and the closed form of a fibonacci number is ((1+sqrt(5))^n - (1-sqrt(5))^n)/(2^n * sqrt(5)) = (φ^n-(1-φ)^n)/sqrt(5) [http://mathworld.wolfram.com/FibonacciNumber.html]
PhilI
@Phil: Yes, I should have checked, at least that case n=0 worked. Far from a pedantic correction; many thanks.
Charles Stewart
+1  A: 

Some of the ways are here, this would also be a nice place to put the solutions you found to.

tadzik