Recursion in Prolog
Our example demonstrates recursive functions in Prolog. Here’s a classic example of factorial calculation.
In Prolog, recursion is a fundamental concept. The fact/2
predicate calculates the factorial of a number. It has a base case fact(0, 1).
and a recursive case for all other numbers.
The fib/2
predicate calculates the Fibonacci sequence. It has two base cases for fib(0, 0)
and fib(1, 1)
, and a recursive case for all other numbers.
To run this program, save it in a file (e.g., recursion.pl
) and use a Prolog interpreter:
This will load the file, call the main/0
predicate, and then exit. The output shows the factorial of 7 (5040) and the 7th Fibonacci number (13).
In Prolog, we don’t need to explicitly declare variables or use closures for recursion. The language naturally supports recursive definitions through its declarative nature and unification mechanism.