Last updated 1 year ago
Was this helpful?
This constructs the fibonacci sequence as a lazy infinite list.
If you really need a function for it:
To support negative indices:
constant @fib = 0, 1, *+* ... *;
sub fib ($n) { @fib[$n] }
constant @neg-fib = 0, 1, *-* ... *; sub fib ($n) { $n >= 0 ?? @fib[$n] !! @neg-fib[-$n] }
sub fib (Int $n --> Int) { $n > 1 or return $n; my ($prev, $this) = 0, 1; ($prev, $this) = $this, $this + $prev for 1 ..^ $n; return $this; }
proto fib (Int $n --> Int) {*} multi fib (0) { 0 } multi fib (1) { 1 } multi fib ($n) { fib($n - 1) + fib($n - 2) }