Prolog is a "declarative" programming language, which means instead of telling the computer
how to do something (like in C or Java), you describe facts and rules about a problem.
For diploma engineering students, these examples cover the fundamental logic used in
database queries, AI, and symbolic math.
1. Family Tree (The Basics)
This is the "Hello World" of Prolog. It defines relationships and uses a rule to determine if
someone is a parent.
Prolog
% Facts
male(tom).
male(bob).
female(alice).
parent(tom, bob).
parent(alice, bob).
% Rule: X is a father of Y if X is male and X is a parent of Y.
father(X, Y) :- male(X), parent(X, Y).
2. Arithmetic: Addition
Prolog uses the is operator to evaluate mathematical expressions.
Prolog
% Usage: add(5, 10, Result).
add(A, B, Sum) :- Sum is A + B.
3. Finding the Maximum of Two Numbers
This uses conditional logic. The semicolon ; acts as an "OR," while the comma , acts as an
"AND."
Prolog
max(X, Y, Max) :- X >= Y, Max is X.
max(X, Y, Max) :- X < Y, Max is Y.
4. Factorial (Recursion)
Recursion is vital in Prolog. We define a "base case" (factorial of 0) and a "recursive rule."
Prolog
factorial(0, 1). % Base case
factorial(N, F) :-
N > 0,
N1 is N - 1,
factorial(N1, F1),
F is N * F1.
5. Membership in a List
Checking if an item exists within a list structure.
Prolog
% Base case: X is the head of the list.
member(X, [X|_]).
% Recursive case: X is in the tail of the list.
member(X, [_|Tail]) :- member(X, Tail).
6. Calculating the Length of a List
This counts how many elements are in a list by stripping the "head" one by one.
Prolog
list_length([], 0). % Empty list has length 0
list_length([_|Tail], L) :-
list_length(Tail, L1),
L is L1 + 1.
7. Even or Odd
A simple check using the modulo operator mod.
Prolog
even(N) :- N mod 2 =:= 0.
odd(N) :- N mod 2 =\= 0.
8. Fibonacci Series
Generating the $N^{th}$ number in the Fibonacci sequence.
Prolog
fib(0, 0).
fib(1, 1).
fib(N, Result) :-
N > 1,
N1 is N - 1, N2 is N - 2,
fib(N1, R1), fib(N2, R2),
Result is R1 + R2.
9. Simple Medical Diagnosis (Mini Expert System)
A classic use case for Prolog logic.
Prolog
symptom(john, fever).
symptse(john, cough).
symptom(mary, headache).
disease(X, flu) :- symptom(X, fever), symptom(X, cough).
disease(X, stress) :- symptom(X, headache).
10. Area of a Circle
Applying a formula ($Area = \pi \times r^2$) in logic form.
Prolog
calculate_area(Radius, Area) :-
Area is 3.14159 * Radius * Radius.
Key Concepts for Exams
Term Definition
Facts Statements that are always true (e.g., male(tom).).
Rules Conclusions based on conditions (using :-).
Atoms Constant values starting with lowercase (e.g., apple).
Variables Placeholders starting with Uppercase (e.g., X).
Would you like me to explain how to install a Prolog interpreter like SWI-Prolog to run
these examples?