Recursion in Dart
Dart supports recursive functions. Here’s a classic example.
import 'dart:io';
// This `fact` function calls itself until it reaches the
// base case of `fact(0)`.
int fact(int n) {
if (n == 0) {
return 1;
}
return n * fact(n - 1);
}
void main() {
print(fact(7));
// Closures can also be recursive, but in Dart, we don't need to
// explicitly declare the type before defining the function.
int Function(int) fib = (int n) {
if (n < 2) {
return n;
}
// Since `fib` was previously declared in `main`, Dart
// knows which function to call with `fib` here.
return fib(n - 1) + fib(n - 2);
};
print(fib(7));
}
To run the program, save it as recursion.dart
and use the dart
command:
$ dart recursion.dart
5040
13
In this Dart example, we’ve implemented the same recursive factorial and Fibonacci functions as in the original code. The main differences are:
We use
import 'dart:io';
instead ofimport "fmt"
for standard I/O operations.The
fact
function is defined outside ofmain
, and its syntax is slightly different from the original, usingint
for type annotations.In Dart, we don’t need to explicitly declare the type of a closure before defining it. We can directly assign the anonymous function to
fib
.We use
print
instead offmt.Println
for output.
The behavior and output of the program remain the same as the original example, demonstrating how recursion works in Dart.