Introduction to Prolog¶
What is Prolog?
Prolog (short for PROgramming in LOGic) is a logic programming language that is very different from languages like Python, Java, or C. Instead of telling the computer how to do something step by step, you tell it facts and rules, and then ask questions.
Prolog is commonly used in: - Artificial Intelligence (AI) - Expert systems - Natural language processing - Rule-based systems
Prolog works by using logic, pattern matching, and backtracking to find answers to questions.
Basic Concepts in Prolog
Facts
Facts are statements that describe relationships or truths. They end with a period.
Example:
likes(john, pizza).
likes(mary, sushi).
likes(john, pasta).
These facts say: - John likes pizza - Mary likes sushi - John likes pasta
Rules
Rules define logic using conditions. They use :- which can be read as “if”.
Example:
food_lover(X) :- likes(X, pizza).
This rule means: - A person X is a food lover if they like pizza
Queries
Queries are questions you ask Prolog. They start with ?- when typed into the Prolog interpreter.
Example:
?- likes(john, pizza).
Prolog will answer:
true.
You can also ask:
?- likes(john, What).
Prolog will return all foods John likes.
Building Simple Prolog Scripts
Creating a Prolog File
Prolog scripts are usually saved with a .pl extension.
Example file name:
family.pl
Example 1: Family Relationships
Below is a simple Prolog script that defines family relationships.
parent(john, mary).
parent(john, sam).
parent(susan, mary).
parent(susan, sam).
father(X, Y) :- parent(X, Y), male(X).
mother(X, Y) :- parent(X, Y), female(X).
male(john).
female(susan).
You can ask questions like:
?- parent(john, mary).
?- father(john, mary).
?- mother(susan, sam).
Example 2: Simple Math Rule
Prolog can also perform simple logic-based math.
double(X, Y) :- Y is X * 2.
Query example:
?- double(5, Result).
Prolog will respond:
Result = 10.
Example 3: Checking Conditions
This example checks if a number is even.
even(X) :- 0 is X mod 2.
Query:
?- even(4).
?- even(7).
Prolog will return true for even numbers and false for odd numbers.
How Prolog Finds Answers
Prolog searches for answers by: - Matching facts and rules - Trying possible solutions - Backtracking if a solution fails
This means Prolog can automatically find multiple answers without writing loops.
Conclusion
Prolog is a powerful language that focuses on logic rather than instructions. By defining facts and rules, you can build intelligent systems that answer complex questions.
Even simple Prolog scripts show how different logic programming is compared to traditional programming languages, making it especially useful for problem-solving and AI-related tasks.