1. Prolog Programming Notes
1. Introduction to Prolog
Prolog (Programming in Logic) is a declarative programming language used for logical
reasoning, AI, and computational linguistics. Prolog focuses on what to solve (logic) rather than
how to solve (procedures).
Main elements:
1. 1. Facts: Represent truths about the world.
2. 2. Rules: Logical relationships between facts.
3. 3. Queries: Questions to the Prolog system to infer knowledge.
2. Prolog Syntax
Facts: Define relationships or properties using predicates.
Example:
loves(john, mary). % John loves Mary
male(john). % John is male
Rules: Define logical conditions using ':-' (if).
Example:
parent(X, Y) :- father(X, Y). % X is parent of Y if X is father of Y
parent(X, Y) :- mother(X, Y). % X is parent of Y if X is mother of Y
Queries: Ask questions to the system using '?-'
Example:
?- loves(john, mary). % Is John in love with Mary?
Yes.
3. Key Components
4. 1. Facts: Statements that are always true.
5. 2. Rules: Logical inference derived from facts.
6. 3. Queries: Questions asked to Prolog.
7. 4. Variables: Denoted by uppercase letters.
4. Execution Flow in Prolog
Prolog uses backtracking to find all possible solutions. If a rule or fact doesnβt satisfy the query,
it tries another path.
Example:
parent(john, mary).
parent(john, peter).
2. ?- parent(john, X).
Result:
X = mary ;
X = peter.
5. Built-in Predicates
Arithmetic: Use 'is' for evaluation.
Example:
sum(X, Y, Z) :- Z is X + Y.
Comparison Operators:
- X > Y, X < Y
- X >= Y, X =< Y
- X =:= Y (equal), X == Y (not equal)
List Operations:
- [Head|Tail] syntax splits a list into its first element (Head) and the rest (Tail).
Example:
member(X, [X|_]).
member(X, [_|Tail]) :- member(X, Tail).
6. Example Programs
Family Tree:
% Facts
father(john, mary).
mother(susan, mary).
father(john, peter).
mother(susan, peter).
% Rules
parent(X, Y) :- father(X, Y).
parent(X, Y) :- mother(X, Y).
sibling(X, Y) :- parent(Z, X), parent(Z, Y), X = Y.
Queries:
?- sibling(mary, peter).
Yes.
?- parent(john, Who).
Who = mary ;
Who = peter.
3. Simple Calculator:
add(X, Y, Z) :- Z is X + Y.
subtract(X, Y, Z) :- Z is X - Y.
multiply(X, Y, Z) :- Z is X * Y.
divide(X, Y, Z) :- Y = 0, Z is X / Y.
Queries:
?- add(5, 3, Result).
Result = 8.
?- divide(10, 2, Result).
Result = 5.
7. Tips for Prolog Programming
8. 1. Always define facts and rules clearly before testing queries.
9. 2. Use comments (%) for better readability.
10. 3. Debug queries by step-by-step evaluation.
11. 4. Test edge cases, especially when using recursion or arithmetic.
8. Advantages of Prolog
12. 1. Natural representation of logic.
2. Built-in pattern matching.
3. Easy to express knowledge and relationships.
4. Great for AI, expert systems, and natural language processing.