September 2017
Beginner
402 pages
9h 52m
English
To summarize our knowledge of multi subs, let's create an example of recursive calculation of the Fibonacci numbers. We will also use type constraints in this code:
multi sub fibonacci(0 --> 0) {}
multi sub fibonacci(1 --> 1) {}
multi sub fibonacci(Int $n --> Int) {
return fibonacci($n - 1) + fibonacci($n - 2);
}
my @fib;
push @fib, fibonacci($_) for 1..10;
@fib.join(', ').say;
The multi subs are used here to bootstrap the recursive fibonacci($n - 1) + fibonacci($n - 2) formula for the values of $n less than 2. The first two variants of the fibonacci sub respond to the values of 0 and 1. Instead of returning an integer in the sub body, we will use the arrow syntax to specify the return value in the signature, as shown here: