Recursion in Wolfram Language
Our first example demonstrates recursion in Wolfram Language. Here’s the full source code:
(* This Factorial function calls itself until it reaches the base case of Factorial[0] *)
Factorial[n_] := If[n == 0, 1, n * Factorial[n - 1]]
(* Main program *)
Print[Factorial[7]]
(* Fibonacci function using recursion *)
Fibonacci[n_] := If[n < 2, n, Fibonacci[n - 1] + Fibonacci[n - 2]]
Print[Fibonacci[7]]
This Factorial
function calls itself until it reaches the base case of Factorial[0]
.
In the main program, we call the Factorial
function with an argument of 7 and print the result.
Wolfram Language also supports recursive functions as first-class objects. Here’s an example with the Fibonacci sequence:
We define the Fibonacci
function using a similar recursive approach. If the input is less than 2, we return the input itself. Otherwise, we recursively call Fibonacci
for n-1
and n-2
and sum the results.
Finally, we call the Fibonacci
function with an argument of 7 and print the result.
To run the program, you can copy this code into a Wolfram Language notebook or a .wl file and evaluate it:
5040
13
The output shows the factorial of 7 (5040) and the 7th Fibonacci number (13).
In Wolfram Language, functions are first-class citizens, so we don’t need to explicitly declare them before use. The language’s pattern matching and functional programming features make it particularly well-suited for recursive algorithms.