Course of Raku / Functional, concurrent, reactive, and web programming / Functional programming / Lazy and infinite sequences / Exercises / The Tribonacci sequence

Solution: The Tribonacci sequence

Here is a possible solution to the task.

Code

my @trib = 1, 1, 1, * + * + * ... *;
say @trib[^8];

🦋 You can find the source code in the file fibonacci.raku.

Output

(1 1 1 3 5 9 17 31)

Comments

  1. The closure * + * + * adds the three previous elements to produce the next, so three starting values are needed.

  2. The sequence is lazy, so storing it in @trib and asking for @trib[^8] computes only the first eight numbers.

Course navigation

The Tribonacci sequence   |   Concurrent programming