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:

  1. We use import 'dart:io'; instead of import "fmt" for standard I/O operations.

  2. The fact function is defined outside of main, and its syntax is slightly different from the original, using int for type annotations.

  3. 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.

  4. We use print instead of fmt.Println for output.

The behavior and output of the program remain the same as the original example, demonstrating how recursion works in Dart.