0% found this document useful (0 votes)
5 views64 pages

Prolog Course

The document outlines a comprehensive Prolog course index, covering topics such as the introduction to Prolog, syntax, unification, backtracking, lists, recursion, arithmetic operations, control structures, and real-world applications. It emphasizes Prolog's declarative nature, allowing users to define relationships and rules rather than procedural steps. The course also includes practical assignments and projects to enhance understanding and application of Prolog concepts.

Uploaded by

Ameer Moavia
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views64 pages

Prolog Course

The document outlines a comprehensive Prolog course index, covering topics such as the introduction to Prolog, syntax, unification, backtracking, lists, recursion, arithmetic operations, control structures, and real-world applications. It emphasizes Prolog's declarative nature, allowing users to define relationships and rules rather than procedural steps. The course also includes practical assignments and projects to enhance understanding and application of Prolog concepts.

Uploaded by

Ameer Moavia
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 64

Prolog Course Index

1. Introduction to Prolog
o What is Prolog?
o History and Applications
o Difference between Procedural and Declarative Programming
o Basic Structure of Prolog Programs
2. Prolog Syntax and Basics
o Facts, Rules, and Queries
o Atoms, Variables, and Data Types
o Constants and Predicates
o Comments and Formatting in Prolog
3. Unification and Backtracking
o Concept of Unification
o Pattern Matching
o How Prolog Searches: Backtracking
4. Lists and Recursion
o List Basics: Representation and Manipulation
o Recursive Definitions in Prolog
o List Processing (Head and Tail)
5. Arithmetic Operations
o Basic Arithmetic in Prolog
o Comparison Operations
o Using Arithmetic with Queries
6. Control Structures
o Conjunctions, Disjunctions, and Negation
o If-Then-Else in Prolog
o Cut Operator (!): Purpose and Use Cases
7. Input and Output
o Reading and Writing Data
o Interactive Input
o File Handling in Prolog
8. Advanced Data Structures
o Trees, Graphs, and Sets in Prolog
o Representation and Traversal
oPathfinding with Prolog
9. Meta-programming in Prolog
o Working with Logic Programs as Data
o Self-modifying Logic
o Reflective Programming in Prolog
10. Debugging and Optimization
o Tracing and Debugging Prolog Programs
o Performance Optimization Techniques
11. Real-world Applications of Prolog
o Expert Systems
o Natural Language Processing
o Knowledge Representation
12. Project and Assignments
o Mini Projects
o Practical Assignments
o Hands-on Practice with Real-world Problems

1. Introduction to Prolog
What is Prolog?

Prolog (Programming in Logic) is a high-level programming language based


on formal logic. Unlike traditional programming languages where the focus
is on providing a sequence of instructions to achieve a result (imperative
programming), Prolog allows the programmer to specify the problem in
terms of facts and rules, and then lets the system figure out the solution by
logically deducing answers. It is specifically designed for applications
involving symbolic reasoning, knowledge representation, and artificial
intelligence (AI).

Prolog works by expressing relationships and logical statements using facts,


rules, and queries. For example, in Prolog, we might express that "Ali is the
father of Zayd" as a fact and then use rules to infer new information, such as
"Zayd is the son of Ali."

History and Applications

Prolog was developed in the early 1970s by Alain Colmerauer and Philippe
Roussel in France, with the goal of creating a language suited for natural
language processing (NLP). It was one of the first languages to implement a
form of automatic reasoning and backtracking, making it a powerful tool for
problem-solving.

Over the years, Prolog has found applications in several fields, particularly in
areas that require symbolic reasoning, such as:

 Artificial Intelligence (AI): Prolog is commonly used for tasks like


expert systems, natural language understanding, and automated
reasoning.
 Database Systems: Prolog's pattern-matching abilities make it useful
for database query languages.
 Theorem Proving: Prolog is used for solving mathematical proofs.
 Logic Programming: It is the standard language for logic programming,
which allows for powerful symbolic problem-solving techniques.
 Decision Support Systems: Many decision-support applications
leverage Prolog for its knowledge inference capabilities.

Some practical examples where Prolog is used include:

 Medical Diagnosis: Using Prolog to infer possible medical conditions


based on symptoms.
 Expert Systems: Prolog is used to create expert systems that can
reason about specific domains like law, finance, or engineering.

Difference between Procedural and Declarative Programming

Prolog is a declarative programming language, which means that in Prolog,


you describe what the solution is, rather than how to achieve it.

 Procedural Programming: In procedural programming languages like C


or Java, the programmer specifies step-by-step instructions on how to
solve a problem. The emphasis is on the procedure or sequence of
steps to follow, and the state of the system changes as each
instruction is executed.

Example in procedural programming:

int factorial(int n) {
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}

 Declarative Programming (Prolog): In Prolog, you focus on defining


the relationships and facts about the problem, and the system handles
finding the solution. The goal is to describe the desired result rather
than the steps to get there. Prolog queries ask questions, and Prolog
answers by searching through the facts and rules provided by the
programmer.

Example in Prolog:

prolog

factorial(0, 1).
factorial(N, F) :- N > 0, N1 is N - 1,
factorial(N1, F1), F is N * F1.

In the above Prolog code, you simply describe the facts (like factorial of 0 is
1) and the rules (how to calculate factorial for other numbers), and Prolog
will deduce the answer when queried.

Basic Structure of Prolog Programs

A Prolog program consists of facts, rules, and queries:

1. Facts: These are basic assertions about the world, which Prolog stores
in its knowledge base.
o Example: "Ali is the father of Zayd."

prolog

father(ali, zayd).

This fact tells us that Ali is the father of Zayd.

2. Rules: Rules define relationships and allow Prolog to infer new facts
based on existing facts. A rule consists of a head (the conclusion) and a
body (the conditions that must be true for the head to be true).
o Example: "If X is the father of Y, and Y is the father of Z, then X is
the grandfather of Z."
prolog

grandfather(X, Z) :- father(X, Y), father(Y, Z).

This rule states that X is the grandfather of Z if X is the father of Y, and


Y is the father of Z.

3. Queries: A query is how you ask Prolog for information. The system
will attempt to match the query with the facts and rules in its
knowledge base.
o Example: "Who is Zayd's father?"
prolog

?- father(X, zayd).

Prolog will respond with X = ali (the value of X is Ali).

4. Variables: In Prolog, variables start with an uppercase letter (e.g., X, Y,


Z), and they are used to represent unknowns in queries and rules.
o Example: A query asking for all fathers:

prolog

?- father(X, Y).

Prolog will return all pairs of X and Y that satisfy the fact or rule about
the father relationship.

This introductory section of Prolog can lay the foundation for understanding
how logic-based programming works. The primary distinction in Prolog lies
in its declarative nature, where the focus is on what needs to be done, and
the system (via backtracking and logical inference) figures out how to
accomplish it.

2. Prolog Syntax and Basics


In Prolog, the syntax is simple but powerful. It allows us to express
knowledge using facts, rules, and queries. These three components form
the backbone of any Prolog program. Let's dive deeper into each of these
concepts and understand how they work.

Facts

A fact in Prolog is a basic assertion about the world that is considered true.
Facts are used to represent static information, like relationships, properties,
or truths about objects. A fact consists of a predicate (a relationship or
property) followed by its arguments.

Syntax:

 Facts are written as a predicate followed by arguments inside


parentheses. Facts are terminated by a period (.).
 A fact does not include any conditions; it simply states that something
is true.

Example:
Consider the relationship "Ali is the father of Zayd." This can be written as a
fact in Prolog as:

prolog

father(ali, zayd).

This statement means that Ali is the father of Zayd.

You can have multiple facts. For example, you can add more relationships:

prolog

father(ali, zayd).
father(ali, hasan).
father(omar, ali).

Here, we have three facts:

 Ali is the father of Zayd.


 Ali is the father of hasan.
 Omar is the father of Ali.
Rules

A rule in Prolog is a conditional statement that defines a relationship


between two or more facts. A rule can be thought of as an if-then
statement.

The left-hand side (called the "body") of a rule contains conditions that
must be true for the right-hand side (called the "head") to be true.

Syntax:

 A rule is written with a head and a body. The head represents the
conclusion, and the body contains conditions that must hold for the
head to be true. The body is separated from the head by :-, which
can be read as "if."
 The rule ends with a period (.).

Example:
Consider the rule "X is the grandfather of Z if X is the father of Y and Y is the
father of Z":

prolog

grandfather(X, Z) :- father(X, Y), father(Y, Z).


head if body (condition)

This rule says that X is the grandfather of Z if X is the father of Y and Y is the
father of Z. The :- can be read as "if," and the comma (,) means "and."

So, given the facts we wrote earlier:

prolog

father(ali, zayd).
father(ali, hasan).
father(omar, ali).

Prolog can infer that ali is the grandfather of zayd (through the rule we
just defined) because ali is the father of hasan and hasan is the father
of zayd.

Queries

A query in Prolog is how we ask the system for information based on the
facts and rules in the program. A query is a question that we ask Prolog, and
the system tries to match it with the facts and rules in the knowledge base.

Syntax:

 A query is written as a question, followed by a question mark (?-).


 Prolog attempts to find all possible answers to the query based on the
information provided.

Example:
Let's say we want to find out who Zayd's father is. We can write a query like
this:

prolog

?- father(X, zayd).

This query asks Prolog to find the value of X such that father(X, zayd)
is true. Prolog will search the knowledge base and will return X = ali,
because the fact father(ali, zayd) exists.

You can also query multiple facts at once. For example:

prolog

?- father(ali, X), father(X, zayd).


This query asks Prolog to find someone who is the father of Zayd and whose
father is Ali. Prolog will return X = hasan because father(ali,
hasan) and father( hasan, zayd) are both true.

Variables

In Prolog, variables are used to represent unknown values in queries, facts,


and rules. Variables start with an uppercase letter, such as X, Y, or Z. When
Prolog encounters a variable in a query or rule, it tries to find values for the
variable that satisfy the conditions.

Example:
The following query uses a variable X to ask who is Zayd’s father:

prolog

?- father(X, zayd).

Here, Prolog will try to match the fact father(ali, zayd) and conclude
that X = ali.

Negation

In Prolog, negation is used to express that something is not true. This is


done using the \+ operator, which can be read as "not."

Example:
If we want to know if Zayd’s father is not Ali, we can write the following
query:

prolog

?- \+ father(ali, zayd).

This query asks Prolog to check if the fact father(ali, zayd) is false. If
it is false, the query will succeed; otherwise, it will fail.
Lists in Prolog

Prolog also supports lists, which are ordered collections of elements. Lists
are written with square brackets [], and elements inside the list are
separated by commas.

Example:
A list of numbers could be written as:

prolog

[1, 2, 3, 4, 5]

To represent a list of facts:

prolog

parent_of([ali, zayd, hasan]).


Operators in Prolog

Prolog also supports various operators, such as:

 Equality: =, which checks if two terms are equal.


 Inequality: \=, which checks if two terms are not equal.
 Arithmetic Operators: +, -, *, / for basic arithmetic operations.

Example:
To check if two variables are equal:

prolog

?- X = Y.

To check if a number is greater than another:

prolog

?- 5 > 3.
Summary
 Facts: Basic assertions that are always true.
 Rules: Conditional statements that define relationships based on facts.
 Queries: Questions that ask the system for information based on facts
and rules.
 Variables: Represent unknowns in queries and rules.
 Negation: Used to express the opposite of a fact.
 Lists: Ordered collections of elements.
 Operators: Used to perform operations like equality and arithmetic.

3. Atoms, Variables, and Data Types


In Prolog, understanding the basic building blocks such as atoms, variables,
and data types is crucial for constructing meaningful and valid programs.
Let’s break each of these components down in detail.

Atoms

An atom in Prolog is the simplest type of term. Atoms are used to represent
constant values, names, or identifiers. They are the most basic form of data
and can be used as facts or predicates. Atoms can be:

 Lowercase letters (e.g., john, mango, school).


 Quoted strings (e.g., 'Ali', 'a string with spaces').

Examples:

prolog

father(ali, zayd).

In this case, ali and zayd are atoms representing individuals.


Atoms are often used to represent names, properties, or identifiers in
Prolog. They can be combined with variables in facts and rules.

Variables

In Prolog, variables are placeholders that represent unknown values.


Variables start with an uppercase letter or an underscore (_), and they are
used in queries and rules to represent values that will be filled in later by
Prolog.

Examples:

prolog

father(ali, X).

Here, X is a variable that represents an unknown individual who is the child


of Ali. When Prolog queries this rule, it will attempt to assign a value to X.

Variables are used to find relationships and infer conclusions. They can
represent any object or value that satisfies a particular condition.

Data Types in Prolog

Prolog is a logic programming language, and its data types are quite flexible.
The primary data types in Prolog are:

1. Atoms: As described earlier, these are constant values that can be


used in facts and rules.
2. Numbers: Prolog supports both integer and floating-point numbers.
Arithmetic operations can be performed on numbers using Prolog's
built-in arithmetic operators.
o Example: 5, 3.14
3. Variables: Represent unknowns or placeholders for values.
o Example: X, Person
4. Lists: An ordered collection of terms, written in square brackets. Lists
can contain atoms, numbers, or other lists.
o Example: [1, 2, 3], [ali, zayd, hasan]
5. Structures: Prolog allows you to create complex terms by combining
atoms and/or variables. These are often used to represent more
complicated objects.
o Example: person(ali, 35) could represent a person named
Ali who is 35 years old.

4. Constants and Predicates


Constants

In Prolog, constants are values that remain the same throughout the
program. Constants can be:

 Atoms: As discussed earlier, these are constant identifiers like ali,


mango, school.
 Numbers: Both integers and floating-point numbers are considered
constants.

Example:

prolog

age(ali, 30).

Here, ali is a constant representing a person, and 30 is a constant


representing their age.

Predicates

A predicate in Prolog is a function or relationship that defines a connection


between entities. Predicates can be thought of as logical assertions that
connect arguments (which can be constants or variables).
A predicate is essentially the name of a relationship, and it is used to
represent facts and rules in Prolog. It is written with a name and arguments
enclosed in parentheses, followed by a period.

Example:

prolog

father(ali, zayd).

Here, father is a predicate that asserts a relationship between ali and


zayd. The predicate can be used in facts, rules, and queries.

More Examples:

 married(ali, hasan). – A fact stating that Ali is married to


hasan.
 parent(ali, zayd). – A predicate stating that Ali is a parent of
Zayd.

Predicates can also be used in rules to define more complex relationships.

Example:

prolog

grandfather(X, Z) :- father(X, Y), father(Y, Z).

Here, the predicate grandfather/2 is defined using two facts: father/2


and father/2. The rule states that X is the grandfather of Z if X is the
father of Y, and Y is the father of Z.

5. Comments and Formatting in Prolog


Prolog allows us to add comments and format our code to improve
readability. Proper use of comments and consistent formatting is essential
when writing Prolog programs, especially for debugging and collaborating
with others.

Comments in Prolog

Prolog supports two types of comments:

1. Single-line comments: These comments start with a percent sign (%).


Anything after the % on the same line is ignored by the Prolog
interpreter.

Example:

prolog

% This is a single-line comment


father(ali, zayd). % This fact states that Ali is
the father of Zayd

2. Multi-line comments: These comments start with /* and end with */.
They can span multiple lines and are useful for longer explanations or
temporarily disabling sections of code.

Example:

prolog

/*
This is a multi-line comment.
It can span several lines and is useful for longer
explanations.
*/
father(ali, zayd).
Formatting Prolog Code

Good formatting is key to writing clear and maintainable Prolog code. Here
are a few tips:
 Indentation: Indent the body of rules to show that it is a part of the
rule.

Example:

prolog

grandfather(X, Z) :-
father(X, Y),
father(Y, Z).

 Spacing: Use consistent spacing around operators (:-, ,, .) to


improve readability.

Example:

prolog

married(ali, hasan).
father(ali, zayd).

 Period (.): Each fact or rule must end with a period (.). It’s important
not to forget this, as Prolog uses it to mark the end of a statement.

Example:

prolog

parent(ali, zayd).

 Clear Names: Use meaningful names for predicates, constants, and


variables to make the code self-explanatory.

Summary of Key Concepts


 Atoms: Constants like ali, school, or 'a string with spaces'
that represent basic pieces of data.
 Variables: Represent unknowns in Prolog, denoted by capitalized
names or underscores (e.g., X, Y).
 Data Types: Prolog supports atoms, numbers, variables, lists, and
structures as its core data types.
 Constants and Predicates: Constants are unchanging values, while
predicates define relationships or properties between terms.
 Comments: Prolog supports single-line and multi-line comments for
documentation and clarity.
 Formatting: Proper indentation, spacing, and use of periods help keep
Prolog code readable and maintainable.

By understanding these basics of Prolog syntax, students will be able to


structure their programs correctly and communicate their logic in a clear
and organized way.

6. Unification and Backtracking


Unification and backtracking are two fundamental concepts in Prolog that
allow it to search for solutions to queries and derive conclusions based on
rules and facts. Understanding how Prolog uses unification and backtracking
is key to mastering how the language works. Let's explore these concepts in
detail.

Concept of Unification

Unification is the process by which Prolog attempts to make two terms


identical by finding a common set of variable assignments. In simpler terms,
unification is the mechanism that matches terms (facts, rules, or queries) by
substituting variables with specific values. If two terms can be unified,
Prolog proceeds with the next step in solving a query or rule; if they cannot
be unified, Prolog backtracks to try another solution.

How Unification Works:


 When Prolog tries to match a fact, rule, or query with a predicate, it
unifies the terms by comparing them.
 If the terms are identical, Prolog considers them as matching.
 If the terms contain variables, Prolog substitutes the variables with the
terms that make both sides identical.

Example of Unification:
Consider the following rule:

prolog

father(ali, X) :- parent(ali, X).

Here, father(ali, X) is a goal, and parent(ali, X) is the rule. When


Prolog tries to satisfy this goal, it will attempt to unify the term
father(ali, X) with any facts or rules that match it.

Let’s say we have the fact:

prolog

parent(ali, zayd).

Unification happens when Prolog matches father(ali, X) with


parent(ali, zayd). The term X in the father predicate gets unified
with zayd, so Prolog knows that X = zayd.

Thus, after unification, the query father(ali, X) would succeed with X


= zayd.

Pattern Matching

Pattern Matching is a core concept in unification. It refers to the process by


which Prolog compares two terms (one being a pattern and the other a goal
or query) to check if they can be unified. If the terms match, Prolog
proceeds with the next step. If not, it backtracks to try different possibilities.
When Prolog matches a pattern, it compares the structure of the terms,
including:

 Atoms: If two atoms are the same, they match.


 Variables: A variable can match any term, and Prolog will bind the
variable to that term.
 Complex Terms: If a term is a structure (e.g., parent(ali, zayd)),
Prolog compares the functor and the arguments in both terms for
equality.

Example of Pattern Matching:


Given the fact:

prolog

parent(ali, zayd).

And the query:

prolog

parent(ali, X).

Prolog tries to unify the pattern parent(ali, X) with the fact


parent(ali, zayd). Since ali matches ali in the fact, and X can match
zayd, the query succeeds, and Prolog binds X = zayd.

Another example:

prolog

parent(ali, X).

If the knowledge base contains the facts:

prolog

parent(ali, zayd).
parent(ali, hasan).

Prolog will unify parent(ali, X) with each fact one by one:

1. First, X = zayd.
2. Then, Prolog will backtrack and try the next possible solution, X =
hasan.

How Prolog Searches: Backtracking

Backtracking is the process Prolog uses to systematically search for all


possible solutions to a query by exploring different options, trying out
different rules, and going back to previous points when it reaches a dead
end. If Prolog reaches a point where no further solutions can be found, it
"backtracks" to the most recent choice point and tries an alternative
solution.

The process of backtracking happens as follows:

1. Prolog tries to satisfy the query: It starts by attempting to match the


query with facts or rules.
2. If a match is found, Prolog proceeds: It keeps working through the
query by matching terms, unifying them, and solving subgoals.
3. If no match is found (failure): Prolog backtracks to the most recent
decision point, un-unifies the variables, and tries the next possible
solution.
4. If all options are exhausted: When Prolog has no more solutions to
try, it terminates and reports failure.

Backtracking Example

Consider the following facts and rule:

prolog

father(ali, zayd).
father(ali, hasan).
father(omar, ali).

grandfather(X, Z) :- father(X, Y), father(Y, Z).

Now, if we query:

prolog

?- grandfather(X, Z).

Prolog will start with the grandfather rule:

 It first tries to unify grandfather(X, Z) with the head of the rule


father(X, Y), father(Y, Z).
 Prolog starts with the first fact father(X, Y) and tries to unify it
with available facts. It finds that father(ali, zayd) and
father(ali, hasan) can unify with the first father(X, Y).

For father(ali, zayd):

 Prolog then tries father(Y, Z) with father(zayd, Z), but this


fails because no father(zayd, Z) fact exists in the knowledge
base.
 Backtracking occurs: Prolog undoes the last successful match
(father(ali, zayd)) and tries the next possibility, father(ali,
hasan).

Now, Prolog will try father(ali, hasan) and proceed similarly. If


Prolog reaches a point where no more matches are possible, it will backtrack
further and continue exploring all available options until the entire query is
exhausted.

Example with Multiple Solutions

Let's consider the following facts:

prolog
parent(ali, zayd).
parent(ali, hasan).
parent(omar, ali).
parent(ali, maryam).

Now, let's query:

prolog

?- parent(ali, X).

Prolog will:

1. Try the first fact, parent(ali, zayd), and return X = zayd.


2. Backtrack and try the next fact, parent(ali, hasan), returning X
= hasan.
3. Backtrack again and try the next, parent(ali, maryam), returning
X = maryam.
4. Finally, Prolog will return false once all options are exhausted.

Thus, Prolog finds all possible solutions through backtracking and


unification.

Summary of Key Concepts


 Unification: The process by which Prolog tries to make two terms
identical by finding common variable assignments.
 Pattern Matching: The mechanism through which Prolog compares
terms and tries to unify them, often involving variables and constants.
 Backtracking: The process by which Prolog systematically searches for
solutions by trying different possibilities and "backtracking" when a
dead end is reached.
o Prolog tries a solution, and if it fails, it backtracks to the most
recent choice point and attempts another solution.
o This process allows Prolog to explore all possible paths for
satisfying a query.

By mastering unification and backtracking, students will understand how


Prolog searches for and finds solutions to complex queries, making it an
extremely powerful language for logic-based problem solving.

7. Lists and Recursion


In Prolog, lists are one of the most essential data structures. They allow you
to group multiple elements together and represent complex relationships.
Recursion, on the other hand, is a technique where a rule or function calls
itself to solve a smaller subproblem. Together, lists and recursion form a
powerful combination for solving problems in Prolog.

Let’s break down lists and recursion in Prolog in deep detail.

List Basics: Representation and Manipulation


What is a List in Prolog?

A list in Prolog is a data structure that can store multiple items, which can be
atoms, numbers, variables, or even other lists. Lists are ordered collections,
meaning the order of the elements matters.

In Prolog, a list is represented using square brackets ([]). The list can be
empty or can contain one or more elements. If the list is not empty, it
consists of a head (the first element) and a tail (the remaining elements of
the list).

Syntax for Lists:

 An empty list is written as [].


 A non-empty list is written as [Head|Tail], where Head is the first
element, and Tail is the remainder of the list (which could be
another list).

Examples:

 Empty list: []
 Non-empty list: [1, 2, 3] (This is a list with three elements: 1, 2,
and 3)
 Another example: [head|[tail]] (This is a list where head is the
first element, and tail is a list itself)

The head is the first element, and the tail is the remaining part of the list. In
Prolog, lists are constructed recursively, meaning that the tail of a list can
itself be another list.

Accessing Elements in a List

To manipulate lists, Prolog uses two primary concepts: the head and the tail
of a list.

 The head of a list is the first element. For example, in the list [1, 2,
3], 1 is the head.
 The tail is the remainder of the list after the head. For example, in the
list [1, 2, 3], the tail is [2, 3].

In Prolog, you can extract the head and tail of a list using pattern matching.

Example:

prolog

?- [X|Tail] = [1, 2, 3].

Here, X will be unified with 1 (the head), and Tail will be unified with [2,
3] (the tail).
Basic List Operations

1. Appending Lists: You can join two lists together using the append/3
predicate.
prolog

append([1, 2], [3, 4], Result).


Result = [1, 2, 3, 4].

2. Length of a List: The length of a list can be determined using the


length/2 predicate.

prolog

length([1, 2, 3], L).


L = 3.

3. Checking if a List is Empty: Prolog can check if a list is empty by using a


simple check for [].
prolog

is_empty([]).
is_empty([_|_]) :- fail. % Fail for non-empty lists

4. Member Checking: You can check if an element exists in a list using


the member/2 predicate.
prolog

member(X, [1, 2, 3]).


X = 1 ;
X = 2 ;
X = 3 ;
false.

5. Head and Tail Extraction: Extracting the head and tail of a list is often
done by matching the list pattern [Head|Tail].
prolog

head_tail([1, 2, 3], Head, Tail).


Head = 1,
Tail = [2, 3].
List Operations in Prolog

Some common operations that can be performed on lists are:

1. Concatenation of Lists:
prolog

append([1, 2], [3, 4], Result).


Result = [1, 2, 3, 4].

Prolog uses backtracking to find all solutions to append operations.

2. Reversing a List:
You can reverse a list in Prolog using recursion. For example:
prolog

reverse([], []).
reverse([Head|Tail], Reversed) :-
reverse(Tail, ReversedTail),
append(ReversedTail, [Head], Reversed).

Recursion in Prolog
What is Recursion?

Recursion is a technique where a rule calls itself to solve a smaller or simpler


version of the same problem. In Prolog, recursion is used extensively to
work with data structures like lists, trees, and graphs. A common use of
recursion in Prolog is to process lists, where the list is reduced step by step
(usually by removing the head and working with the tail) until the base case
is reached.

Recursive Definition of List Operations

1. Finding the Length of a List (Using Recursion)

The length of a list can be found by recursively traversing the list, counting
one element at a time. When the list is empty ([]), the length is 0 (base
case).

prolog

length([], 0). % Base case: length of an empty list is


0
length([_|Tail], N) :-
length(Tail, N1),
N is N1 + 1. % Recursively calculate length of the
tail

For example, if we query length([1, 2, 3], N)., Prolog will


recursively call length/2 until it reaches the base case (empty list), and
then calculate the length.

2. Sum of Elements in a List (Using Recursion)

You can also sum the elements of a list by recursively adding the head of the
list to the sum of the tail.

prolog

sum([], 0). % Base case: sum of an empty list is 0


sum([Head|Tail], Total) :-
sum(Tail, TailSum),
Total is Head + TailSum. % Add head to sum of the
tail
For the query sum([1, 2, 3], Total)., Prolog will compute the sum
as follows:
1 + (2 + (3 + 0)).

3. Reversing a List (Using Recursion)

Reversing a list is a common task and is often done recursively by moving


the head to the tail of the reversed list.

prolog

reverse([], []). % Base case: reversing an empty list


is an empty list
reverse([Head|Tail], Reversed) :-
reverse(Tail, ReversedTail),
append(ReversedTail, [Head], Reversed).

Here, Prolog recursively calls reverse/2 to reverse the tail, and then
appends the head at the end of the reversed tail.

Recursion with Lists: A Deeper Understanding


In Prolog, lists are handled using a divide and conquer approach, where
recursion breaks down the problem into smaller subproblems. Each
recursive call works with a smaller part of the list, and when the base case is
reached, the recursion begins to return.

For example, consider the rule for summing a list:

 The base case handles the empty list by returning 0.


 The recursive case processes the head of the list and adds it to the
sum of the remaining elements (i.e., the tail).

Efficiency Considerations
Prolog’s recursive approach is elegant but can be inefficient if not used
carefully, especially for large lists. Some strategies to improve efficiency
include:

 Tail Recursion: This is a special form of recursion where the recursive


call is the last operation performed. Tail recursion avoids creating new
stack frames for each recursive call, which can improve performance
for large inputs.
 Accumulators: You can use an accumulator in the recursive process to
store intermediate results, reducing the need for backtracking.

Summary of Key Concepts


 Lists: In Prolog, lists are ordered collections of terms, represented by
square brackets ([]). Lists can be empty or non-empty, where non-
empty lists are constructed as [Head|Tail].
 Recursion: Recursion is a technique where a rule calls itself to solve a
smaller version of the problem. It is used to process lists and other
data structures in Prolog.
 List Operations: Common list operations in Prolog include finding the
length, reversing, summing, appending, and checking for membership.
 Recursion with Lists: Prolog solves list problems by recursively
processing the head and tail of the list, reducing the problem size at
each step until reaching a base case.

By understanding lists and recursion in Prolog, students can solve a wide


range of problems, from simple tasks like reversing a list to more complex
ones like graph traversal or tree manipulations.

8. Recursive Definitions in Prolog


In Prolog, recursion is a powerful method used to define rules and solve
problems, particularly when dealing with data structures like lists. Recursive
definitions are essential in Prolog because they allow you to break down
complex problems into smaller, more manageable subproblems. This
method works by having a rule call itself to solve a problem until a base case
is reached.

Let’s go deeper into recursive definitions in Prolog and how they work, with
plenty of examples.

Understanding Recursive Definitions

A recursive definition in Prolog typically consists of:

1. Base Case: The simplest version of the problem, often used to stop the
recursion. It defines what happens when the problem is trivially
solved.
2. Recursive Case: This defines the problem in terms of smaller or
simpler versions of itself. It calls the same rule with a smaller problem,
gradually approaching the base case.

In Prolog, the recursion is usually seen in the way you define rules for lists.
For example, a rule that sums a list recursively would need a base case to
handle the empty list and a recursive case to add the head of the list to the
sum of the tail.

Recursive Sum Example

Let’s say we want to define a recursive rule to compute the sum of the
elements in a list. Here's how it works:

prolog

% Base case: The sum of an empty list is 0


sum([], 0).

% Recursive case: The sum of a list is the head plus


the sum of the tail
sum([Head|Tail], Total) :-
sum(Tail, TailSum), % Recursively calculate
sum of the tail
Total is Head + TailSum. % Add the head to the sum
of the tail
Explanation of the Recursive Sum Rule:

1. Base Case (sum([], 0)): This is the simplest possible list, an empty
list. We define that the sum of an empty list is 0.
2. Recursive Case (sum([Head|Tail], Total)): If the list is not
empty, we break it into the Head (the first element) and the Tail
(the rest of the list). The rule then calls itself with the Tail and adds
the Head to the sum of the Tail.

How It Works:

 Query: sum([1, 2, 3], Total).


o The rule first takes 1 as the Head and [2, 3] as the Tail.
o It recursively calls sum([2, 3], TailSum).
o For sum([2, 3], TailSum), it calls sum([3], TailSum2).
o Finally, for sum([3], TailSum2), it calls sum([], 0) (the
base case), returning 0.
o As it backtracks, the sums are added: 3 + 0 = 3, then 2 + 3
= 5, and finally 1 + 5 = 6.
o So, Total = 6.

This example shows how recursion allows Prolog to solve problems by


breaking them down into simpler subproblems.

9. List Processing (Head and Tail)


In Prolog, list processing often involves working with the head and tail of a
list. The head is the first element of the list, and the tail is the rest of the list.
List processing rules typically break a list into its head and tail and then
recursively process the tail.
Structure of Lists

A list in Prolog is defined as:

prolog

[Head|Tail]

 Head: The first element of the list.


 Tail: The remaining list (which can be empty or contain other
elements).

When working with lists, Prolog’s pattern matching mechanism allows you
to easily access and manipulate the head and tail.

Processing the Head and Tail Recursively

Let's look at how Prolog processes lists using recursion with examples.

1. Reversing a List

To reverse a list, we recursively move through the list, taking the head and
putting it at the end of the reversed tail.

prolog

% Base case: The reverse of an empty list is an empty


list
reverse([], []).

% Recursive case: Reverse the tail, then append the


head to the reversed tail
reverse([Head|Tail], Reversed) :-
reverse(Tail, ReversedTail), % Recursively
reverse the tail
append(ReversedTail, [Head], Reversed). % Append
the head to the reversed tail
Explanation:

 The base case says that the reverse of an empty list is itself (an empty
list).
 The recursive case first reverses the tail of the list, and then the head
is appended to the reversed tail.

How It Works:

 Query: reverse([1, 2, 3], Reversed).


o The list [1, 2, 3] is split into Head = 1 and Tail = [2,
3].
o It recursively calls reverse([2, 3], ReversedTail),
which further splits into Head = 2 and Tail = [3].
o The process continues until reverse([], []) is called,
returning [].
o As Prolog backtracks, it appends the heads in reverse order:
append([], [3], [3]), then append([3], [2], [3,
2]), and finally append([3, 2], [1], [3, 2, 1]).
o The final result is Reversed = [3, 2, 1].

2. Finding the Length of a List

The length of a list can be calculated recursively by counting each element in


the list until it reaches an empty list.

prolog

% Base case: The length of an empty list is 0


length([], 0).

% Recursive case: The length of a non-empty list is 1 +


the length of the tail
length([_|Tail], Length) :-
length(Tail, TailLength), % Recursively find the
length of the tail
Length is TailLength + 1. % Add 1 to the length
of the tail
Explanation:

 The base case says that the length of an empty list is 0.


 The recursive case calls length/2 on the tail of the list, and adds 1
for each element (the head).

How It Works:

 Query: length([1, 2, 3, 4], Length).


o For length([1, 2, 3, 4], Length), it matches Head =
1 and Tail = [2, 3, 4].
o It recursively calls length([2, 3, 4], TailLength), and
so on, until length([], 0) is reached.
o As Prolog backtracks, it adds 1 for each element in the list: 1 +
1 + 1 + 1 = 4.
o The final result is Length = 4.

3. Appending Two Lists

Appending two lists in Prolog involves recursively traversing the first list and
placing its elements at the beginning of the second list.

prolog

% Base case: The append of an empty list with another


list is the other list
append([], List, List).

% Recursive case: Append the head of the first list


with the append of the tail
append([Head|Tail], List, [Head|Result]) :-
append(Tail, List, Result). % Recursively append
the tail of the first list to the second list
Explanation:

 The base case says that appending an empty list to any list results in
the other list.
 The recursive case takes the Head of the first list and appends it to the
result of appending the Tail of the first list to the second list.

How It Works:

 Query: append([1, 2], [3, 4], Result).


o append([1, 2], [3, 4], Result) matches the head 1
and tail [2].
o It recursively calls append([2], [3, 4], Result2), and
then append([], [3, 4], Result3), which returns [3,
4].
o As Prolog backtracks, it builds the result: Result = [1, 2,
3, 4].

Conclusion on Recursive Definitions and List Processing


 Recursive Definitions: Prolog uses recursion to break down problems
into simpler subproblems, with each step of recursion operating on a
smaller version of the problem. This technique is used to solve
problems involving lists, trees, and other data structures.
 List Processing: Working with lists in Prolog typically involves
processing the head and tail of the list. Recursion is used extensively
to handle the tail of a list, while the head is processed at each step.
 Key Concepts:
o Base case: Defines how to handle the simplest version of the
problem.
o Recursive case: Defines how to reduce the problem to smaller
subproblems.
o Head and Tail: The head is the first element, and the tail is the
remainder of the list.
o Efficiency: Recursion can be inefficient for very large lists, so
techniques like tail recursion and accumulators are often used
to optimize performance.

By mastering recursive definitions and list processing, Prolog users can


effectively tackle a wide variety of problems that involve sequences,
collections, and structures.

5. Arithmetic Operations in Prolog


Prolog, being a logical programming language, does not inherently operate
with numerical calculations the way procedural languages do. However,
Prolog provides a powerful set of built-in arithmetic operations that allow
you to perform calculations and manipulate numbers. These operations
work with integers and floating-point numbers and are essential for
handling numerical problems.

Let’s explore basic arithmetic operations in Prolog and how you can use
them for solving mathematical problems.

Basic Arithmetic in Prolog

Prolog uses the standard arithmetic operations like addition, subtraction,


multiplication, division, and more, but they are handled in a unique way
using is/2, a built-in operator.

The is/2 Operator

The is/2 operator is used to evaluate arithmetic expressions. It is the main


way in Prolog to perform calculations. It is essential to note that is/2 can
only be used to evaluate arithmetic expressions, and not just any formula
involving variables.

General Syntax of is/2:


prolog
Result is Expression.

Where:

 Expression is an arithmetic expression involving operators like +, -,


*, /, etc.
 Result is the variable that will hold the result of the evaluation.

Common Arithmetic Operators in Prolog

Prolog supports a range of basic arithmetic operators that are used to


perform mathematical calculations. These include:

1. Addition (+):
The + operator is used to add two numbers.
prolog

X is 3 + 5. % X will be 8

2. Subtraction (-):
The - operator is used to subtract one number from another.
prolog

X is 10 - 4. % X will be 6

3. Multiplication (*):
The * operator is used to multiply two numbers.
prolog

X is 4 * 7. % X will be 28
4. Division (/):
The / operator divides the left operand by the right operand and
returns a floating-point result.
prolog

X is 10 / 3. % X will be 3.3333...

5. Integer Division (//):


The // operator performs integer division, meaning it returns the
quotient of the division, discarding any remainder (it returns the result
as an integer).
prolog

X is 10 // 3. % X will be 3

6. Modulus (mod):
The mod operator returns the remainder of a division operation.
prolog

X is 10 mod 3. % X will be 1 (remainder after


dividing 10 by 3)

7. Exponentiation (^):
The ^ operator raises a number to the power of another.
prolog

X is 2^3. % X will be 8

Using Arithmetic Operations with Variables

In Prolog, arithmetic operations typically involve variables. When


performing an operation, you need to use the is/2 operator to evaluate
expressions and bind values to variables.
For example, if you want to calculate the sum of two variables A and B:

prolog

A = 3,
B = 5,
C is A + B. % C will be 8

Here, A and B are variables, and C will be assigned the value of A + B,


which is 8.

Example: Calculating the Area of a Rectangle

Let’s say you want to calculate the area of a rectangle given its length and
width. The formula for the area of a rectangle is:

Area=Length×Width\text{Area} = \text{Length} \times


\text{Width}Area=Length×Width

Here’s how you can define a Prolog rule to compute this:

prolog

% Rule to calculate the area of a rectangle


area_of_rectangle(Length, Width, Area) :-
Area is Length * Width.

Now, you can use this rule to calculate the area of a rectangle with length
10 and width 5:

prolog

?- area_of_rectangle(10, 5, Area).
Area = 50.
Example: Solving a Quadratic Equation

Consider the quadratic equation:

ax2+bx+c=0ax^2 + bx + c = 0ax2+bx+c=0

The solutions for this equation can be found using the quadratic formula:

x=−b±b2−4ac2ax = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}x=2a−b±b2−4ac

Let’s write a Prolog rule that computes the roots of the quadratic equation:

prolog

% Rule to compute the roots of a quadratic equation


quadratic_roots(A, B, C, X1, X2) :-
Discriminant is B^2 - 4*A*C, % Calculate the
discriminant
Discriminant >= 0, % Ensure the
discriminant is non-negative (real roots)
SqrtDiscriminant is sqrt(Discriminant), % Find the
square root of the discriminant
X1 is (-B + SqrtDiscriminant) / (2*A), % First
root
X2 is (-B - SqrtDiscriminant) / (2*A). % Second
root

Now, you can solve for the roots of the quadratic equation 2x2−4x−6=02x^2
- 4x - 6 = 02x2−4x−6=0:

prolog

?- quadratic_roots(2, -4, -6, X1, X2).


X1 = 3,
X2 = -1.

Here, the Prolog rule computes the roots of the quadratic equation and
returns X1 = 3 and X2 = -1 as the solutions.
Handling Floating Point Arithmetic

Prolog can handle both integers and floating-point numbers, but there’s a
key difference in how they are processed:

 Integers: Whole numbers.


 Floating-point numbers: Numbers with decimal points.

For example:

prolog

X is 10 / 3. % X will be 3.3333...

If you wanted the result as an integer, you would use the // operator
(integer division):

prolog

X is 10 // 3. % X will be 3

Summary of Basic Arithmetic Operations in Prolog


Here’s a summary of the key arithmetic operators in Prolog:

 +: Addition
 -: Subtraction
 *: Multiplication
 /: Division (floating point result)
 //: Integer Division (quotient)
 mod: Modulus (remainder)
 ^: Exponentiation

All arithmetic operations in Prolog require the use of the is/2 operator,
which binds the result of the arithmetic expression to a variable.
Conclusion
Arithmetic operations in Prolog are essential for solving numerical problems,
including basic arithmetic, solving equations, and working with
mathematical formulas. By using the is/2 operator, Prolog allows you to
perform a wide range of calculations and manipulate numbers in a
declarative manner. Whether you are solving simple problems or dealing
with complex equations, Prolog's arithmetic capabilities are robust and
flexible, making it a useful tool for logic-based problem-solving.

6. Comparison Operations in Prolog


In Prolog, comparison operations are used to compare two values, usually to
determine whether a condition is true or false. These operations are
typically used in conjunction with queries or rules to perform logical
comparisons between numbers, variables, or expressions.

Comparison Operators in Prolog

Prolog provides a set of built-in comparison operators that allow you to


compare numeric values, variables, and expressions. These operators return
true or false depending on whether the comparison holds.

Here are the most commonly used comparison operators:

1. =:=: Equal to (numerically)


o This operator checks if two numbers are equal. It performs
arithmetic evaluation before making the comparison.
o Example: X =:= 5 checks if X is equal to 5.
2. =\=: Not equal to (numerically)
o This operator checks if two numbers are not equal. It performs
arithmetic evaluation.
o Example: X =\= 5 checks if X is not equal to 5.
3. <: Less than
o This operator checks if one number is less than another.
o Example: X < 5 checks if X is less than 5.
4. >: Greater than
o This operator checks if one number is greater than another.
o Example: X > 5 checks if X is greater than 5.
5. =<: Less than or equal to
o This operator checks if one number is less than or equal to
another.
o Example: X =< 5 checks if X is less than or equal to 5.
6. >=: Greater than or equal to
o This operator checks if one number is greater than or equal to
another.
o Example: X >= 5 checks if X is greater than or equal to 5.

Using Comparison Operators in Prolog

Let’s look at how these operators work in different scenarios:

1. Simple Comparison in Queries

You can use comparison operators in queries to check if certain


conditions hold true. For example:

prolog

?- 5 =:= 5.
true. % 5 is equal to 5

?- 5 =:= 6.
false. % 5 is not equal to 6

Prolog returns true or false based on whether the condition is


satisfied.

2. Comparison with Variables


You can also compare variables in Prolog, but it’s important to
remember that Prolog will attempt to unify variables before
performing the comparison. For instance:

prolog

?- X = 5, X =:= 5.
X = 5. % X is successfully unified with 5, and the
comparison is true

?- X = 5, X =:= 6.
false. % X cannot be both 5 and 6 at the same time

Here, Prolog first unifies the variable X with 5, and then checks if the
comparison X =:= 5 holds true.

3. Example: Age Comparison

Let's write a rule that checks if someone is an adult (age >= 18):

prolog

is_adult(Age) :-
Age >= 18.

Now, you can query whether a person of a certain age is an adult:

prolog

?- is_adult(20).
true.

?- is_adult(16).
false.

7. Using Arithmetic with Queries


Arithmetic can be very powerful in Prolog when used in conjunction with
queries. You can perform calculations and use the results in conditions or
rules to solve problems. Arithmetic operations and comparisons are often
employed to check certain conditions dynamically during query evaluation.

Using Arithmetic in Queries

Prolog allows you to use arithmetic expressions in queries directly, as long as


you use the is/2 operator for evaluation. This makes it easy to perform
calculations and comparisons within the same query.

1. Simple Arithmetic with Queries

You can use the is/2 operator to perform arithmetic and then
compare the result with other values. For instance, if you want to
check if the sum of two numbers equals 10:

prolog

?- X is 3 + 7, X =:= 10.
X = 10.

In this example:

o X is 3 + 7 calculates the sum of 3 and 7 (which is 10).


o X =:= 10 checks if the value of X is equal to 10.
2. Arithmetic in Rules

You can also use arithmetic operations in rules. For example, a rule
might calculate the price after a discount and check if the final price is
within a given budget.

prolog

discounted_price(OriginalPrice, Discount,
FinalPrice) :-
FinalPrice is OriginalPrice * (1 - Discount).
Now, you can query whether a product with a given original price and
discount falls within a certain budget:

prolog

?- discounted_price(100, 0.2, FinalPrice),


FinalPrice =< 80.
FinalPrice = 80.

In this example:

o discounted_price(100, 0.2, FinalPrice) calculates


the discounted price.
o FinalPrice =< 80 checks if the final price is less than or
equal to 80.
3. Using Arithmetic to Solve Word Problems

Let’s say you want to solve a problem where a person’s age is related
to another person’s age. For example, "Sami is 5 years older than Ali."
You can define a Prolog rule that calculates their ages based on a given
age for Ali:

prolog

age_difference(AgeAli, AgeSami) :-
AgeSami is AgeAli + 5.

Now, you can query the age of Sami if Ali’s age is known:

prolog

?- age_difference(25, AgeSami).
AgeSami = 30.

Here, we calculate Sami’s age by adding 5 years to Ali’s age.


Example: Using Arithmetic and Comparison in Complex
Queries
Let’s say you want to solve a query that combines both arithmetic and
comparison. For instance, you want to check if a person’s salary is greater
than a threshold after a bonus has been added. You can use both arithmetic
operations and comparisons in a single query.

prolog

% Rule to calculate the new salary after bonus


new_salary(Salary, Bonus, NewSalary) :-
NewSalary is Salary + Bonus.

% Query to check if the new salary exceeds a certain


threshold
salary_above_threshold(Salary, Bonus, Threshold) :-
new_salary(Salary, Bonus, NewSalary),
NewSalary >= Threshold.

Now, if you want to check if someone’s salary after a bonus exceeds 5000:

prolog

?- salary_above_threshold(4500, 600, 5000).


true.

In this case:

 The new_salary(4500, 600, NewSalary) calculates the new


salary after adding the bonus (4500 + 600 = 5100).
 The NewSalary >= 5000 checks if the new salary is greater than or
equal to 5000.

Conclusion
In Prolog, comparison operations and arithmetic operations are essential
for evaluating conditions, making decisions, and solving problems
dynamically. The key comparison operators (=:=, =\=, <, >, =<, >=) allow
you to compare numeric values and variables, while the is/2 operator is
crucial for performing arithmetic calculations.

 Comparison operations are used to test relationships between values


and variables.
 Arithmetic operations allow you to calculate numeric expressions, and
the results can be used in both rules and queries.
 Using arithmetic in queries enables Prolog to evaluate complex
conditions involving numbers and comparisons, making it a versatile
tool for solving problems that require dynamic evaluation.

By combining arithmetic and comparison operations in your Prolog


programs, you can create more sophisticated rules and queries that solve a
wide range of logical and mathematical problems.

6. Control Structures in Prolog


Control structures in Prolog are used to manage the flow of logic in
programs, determining how Prolog searches through rules and facts. Unlike
traditional procedural programming languages, Prolog operates on a
declarative basis, meaning it describes what should be true rather than
specifying how to compute it. However, Prolog still provides mechanisms to
control the flow of logical deduction through conjunctions, disjunctions,
and negation.

In this section, we’ll dive deep into each of these control structures and their
usage in Prolog.

1. Conjunctions (AND) in Prolog


In Prolog, conjunction is used to express logical AND, meaning that both
conditions need to be true for the overall statement to be true.

Syntax of Conjunction

Conjunctions are represented by a comma (,), which connects two or more


goals (sub-goals). Each goal is a condition or fact that Prolog tries to satisfy.

Example:

Let’s define a rule that checks if someone is eligible to vote, which requires
two conditions:

1. The person must be an adult (age >= 18).


2. The person must be a citizen.

Here’s how the conjunction is used in Prolog to combine these conditions:

prolog

is_eligible_to_vote(Age, Citizen) :-
Age >= 18,
Citizen = true.

 Age >= 18 checks if the person is an adult.


 Citizen = true checks if the person is a citizen.
 The conjunction Age >= 18, Citizen = true ensures both
conditions must hold true.

Now, you can query whether a person with a given age and citizenship is
eligible to vote:

prolog

?- is_eligible_to_vote(20, true).
true.

?- is_eligible_to_vote(16, true).
false.

?- is_eligible_to_vote(20, false).
false.

Explanation:

 For is_eligible_to_vote(20, true), both conditions (Age >=


18 and Citizen = true) are true, so the result is true.
 For is_eligible_to_vote(16, true), the first condition fails
(Age < 18), so the result is false.
 For is_eligible_to_vote(20, false), the second condition
fails (Citizen = false), so the result is false.

Backtracking with Conjunctions

When Prolog evaluates a conjunction, it will try to satisfy each goal from left
to right. If the first goal fails, Prolog will backtrack to the previous choice
point and attempt to find another solution. If the first goal succeeds but the
second fails, Prolog will also backtrack.

2. Disjunctions (OR) in Prolog


In Prolog, disjunction represents logical OR. This means that if any one of
the conditions is true, the overall statement will be true.

Syntax of Disjunction

Disjunctions are represented by a semicolon (;), which connects two or


more goals, where only one needs to succeed for the entire disjunction to
succeed.

Example:

Let’s define a rule that checks if a person is either a student or a teacher:


prolog

is_teacher_or_student(Person) :-
Person = student;
Person = teacher.

 Person = student is the first condition.


 Person = teacher is the second condition.
 The semicolon ; between them means that either Person is a
student or a teacher for the rule to be true.

Now, you can query whether a person is a teacher or a student:

prolog

?- is_teacher_or_student(student).
true.

?- is_teacher_or_student(teacher).
true.

?- is_teacher_or_student(doctor).
false.

Explanation:

 For is_teacher_or_student(student), the first condition


(Person = student) is true, so the rule succeeds.
 For is_teacher_or_student(teacher), the second condition
(Person = teacher) is true, so the rule succeeds.
 For is_teacher_or_student(doctor), neither condition is true,
so the rule fails.

Backtracking with Disjunctions

Prolog tries each condition in the disjunction, and if the first condition fails,
it automatically tries the next one (backtracking). This behavior is similar to
how OR works in traditional programming languages—if one branch fails, it
will continue evaluating the others.

3. Negation in Prolog
In Prolog, negation is used to represent logical NOT. This means that a goal
is true if the negated condition does not hold.

Syntax of Negation

Negation in Prolog is represented using \+, which is a built-in operator that


checks whether a condition does not succeed.

Example:

Let’s define a rule that checks if a person is not eligible to vote. We will use
negation to express that if a person is not an adult or not a citizen, they are
not eligible to vote.

prolog

is_not_eligible_to_vote(Age, Citizen) :-
\+ (Age >= 18),
\+ (Citizen = true).

Here:

 \+ (Age >= 18) means that the person is not an adult.


 \+ (Citizen = true) means that the person is not a citizen.
 Both conditions need to fail for the person to be considered not
eligible to vote.

Now, let’s query whether a person is not eligible to vote:

prolog
?- is_not_eligible_to_vote(16, false).
true.

?- is_not_eligible_to_vote(20, true).
false.

?- is_not_eligible_to_vote(17, true).
true.

Explanation:

 For is_not_eligible_to_vote(16, false), both conditions


are true (Age < 18 and Citizen = false), so the negations
succeed and the result is true.
 For is_not_eligible_to_vote(20, true), neither negation
holds (since the person is both an adult and a citizen), so the result is
false.
 For is_not_eligible_to_vote(17, true), the first negation
(Age < 18) succeeds, so the result is true.

Negation as Failure

In Prolog, negation is sometimes referred to as negation as failure. This


means that Prolog assumes a goal is false if it fails to prove the goal to be
true. For example, if Prolog cannot find a fact or rule that matches the goal,
it will treat the goal as false:

prolog

is_parent_of(john, mary).
is_parent_of(john, tom).

% Check for a negation


?- \+ is_parent_of(john, susan).
true.
Here, Prolog attempts to find whether is_parent_of(john, susan) is
true. Since there’s no fact for john being a parent of susan, Prolog
assumes the negation is true.

Control Structures with Conjunctions, Disjunctions, and


Negation
Complex Example Combining All Three

Let’s put all three control structures (conjunction, disjunction, and negation)
together in a more complex example. We want to check whether a person is
eligible to apply for a job based on several conditions:

1. The person must be either a student or a teacher.


2. The person must not have a criminal record.
3. The person must be an adult.

Here’s how we can represent this in Prolog:

prolog

is_eligible_for_job(Age, CriminalRecord, PersonType) :-


(PersonType = student; PersonType = teacher),
\+ CriminalRecord = true,
Age >= 18.

Now, let’s query the eligibility for different individuals:

prolog

?- is_eligible_for_job(20, false, student).


true.

?- is_eligible_for_job(17, false, teacher).


false.
?- is_eligible_for_job(25, true, student).
false.

?- is_eligible_for_job(22, false, engineer).


false.

Explanation:

 For is_eligible_for_job(20, false, student), the person


is a student, has no criminal record, and is an adult, so the result is
true.
 For is_eligible_for_job(17, false, teacher), the person
is a teacher but not an adult, so the result is false.
 For is_eligible_for_job(25, true, student), the person is
a student but has a criminal record, so the result is false.
 For is_eligible_for_job(22, false, engineer), the
person is not a student or teacher, so the result is false.

Conclusion
 Conjunctions (AND) ensure that all conditions must be true for the
rule to succeed.
 Disjunctions (OR) ensure that at least one condition must be true.
 Negation (NOT) ensures that the goal does not succeed.

In Prolog, these control structures give you the flexibility to express complex
logical conditions, enabling you to model real-world problems in a
declarative and efficient way.

7. Control Structures in Prolog


In Prolog, if-then-else and the cut operator (!) are used to control the flow
of execution and to prune search spaces in certain situations. These control
structures allow you to make decisions based on conditions and optimize
the search process. Let’s dive into both of these topics in detail.
1. If-Then-Else in Prolog
In Prolog, the if-then-else construct is used to define rules where different
actions are taken depending on a condition. This is similar to the if-else
statement in procedural programming languages. The general structure is:

prolog

condition -> Action1; Action2.

Where:

 condition is the condition that will be checked.


 Action1 is the action executed if the condition is true.
 Action2 is the action executed if the condition is false.

This is implemented using the semicolon (;), which denotes disjunction


(OR). However, in the case of if-then-else, Prolog uses -> to represent the
if-then part and ; for the else part.

Syntax
prolog

condition -> Action1 ; Action2.

 If the condition succeeds, then Action1 will be executed.


 If the condition fails, then Prolog will try Action2.

Example:

Let’s define a simple rule to determine whether a number is positive,


negative, or zero:

prolog

check_number(Number) :-
Number > 0 ->
write('Positive');
Number < 0 ->
write('Negative');
write('Zero').

This rule works as follows:

 If Number > 0, it will print "Positive".


 If Number < 0, it will print "Negative".
 If neither condition is true (i.e., the number is zero), it will print
"Zero".

Now, you can query the rule:

prolog

?- check_number(5).
Positive.

?- check_number(-3).
Negative.

?- check_number(0).
Zero.

Explanation:

 For check_number(5), since 5 > 0, the first action is executed and


the output is "Positive".
 For check_number(-3), since -3 < 0, the second action is
executed and the output is "Negative".
 For check_number(0), neither Number > 0 nor Number < 0 is
true, so the final action write('Zero') is executed.
Use Case:

You can use this construct when you need to make decisions based on
certain conditions. For example, choosing between different actions based
on whether a person’s age qualifies them for a discount:

prolog

apply_discount(Age, Price) :-
(Age > 60 ->
DiscountedPrice is Price * 0.8 ; % 20% discount
for seniors
Age < 18 ->
DiscountedPrice is Price * 0.9 ; % 10% discount
for minors
DiscountedPrice = Price), % no discount for others
write('Discounted Price: '),
write(DiscountedPrice).

Query:

prolog

?- apply_discount(65, 100).
Discounted Price: 80.

?- apply_discount(15, 100).
Discounted Price: 90.

?- apply_discount(30, 100).
Discounted Price: 100.

In this case:

 If Age > 60, a 20% discount is applied.


 If Age < 18, a 10% discount is applied.
 Otherwise, no discount is given.
2. The Cut Operator (!) in Prolog
The cut operator (!) is a special Prolog operator used to control the search
space during the evaluation of a goal. It is used to prune the search by
preventing Prolog from backtracking past the point where the cut is placed.

Purpose of the Cut Operator

The cut operator is used to:

 Prevent Prolog from exploring alternative solutions once a certain rule


has been successfully executed.
 Improve efficiency by reducing unnecessary backtracking.
 Control the flow of execution and ensure that only specific solutions
are found.

In simple terms, the cut operator commits Prolog to the current path of
execution and prevents backtracking beyond that point.

How the Cut Works

When Prolog encounters the cut (!), it commits to the current choice point
and removes all alternatives to that point. If Prolog reaches the cut while
trying to find solutions, it will not backtrack to earlier points and will not
attempt other rules or facts.

Syntax
prolog

goal1, !, goal2.

 goal1 will be attempted.


 If goal1 succeeds, Prolog will execute the cut (!) and will not
backtrack to other possible alternatives for goal1.
 goal2 will be executed after the cut if goal1 is true.
Example 1: Using the Cut in a Simple Rule

Let’s define a rule that checks if a number is positive or negative:

prolog

check_sign(Number) :-
Number > 0,
!,
write('Positive').
check_sign(Number) :-
Number < 0,
write('Negative').

Here:

 If Number > 0 is true, Prolog will execute the first rule and then
commit to this solution by using the cut (!). This means that even if
there are other facts or rules that could be tried, Prolog will not go
back and try them.
 If Number < 0 is true, Prolog will execute the second rule (without
backtracking to the first rule due to the cut in the first one).

Now, let’s query this:

prolog

?- check_sign(5).
Positive.

?- check_sign(-3).
Negative.

Explanation:

 In the first query check_sign(5), the condition Number > 0 is


true. The cut ! is executed, so Prolog does not backtrack and attempt
the second rule.
 In the second query check_sign(-3), Number > 0 fails, so Prolog
proceeds to the second rule without any need for backtracking.

Example 2: Using the Cut to Optimize Search

Suppose we have a set of rules that check a person's eligibility for a loan
based on their age and credit score. If the person is under 18 or has a bad
credit score, they are not eligible. After checking the first condition (age), if
the person is ineligible based on age, we don’t need to check their credit
score:

prolog

eligible_for_loan(Age, CreditScore) :-
Age >= 18,
CreditScore >= 700,
!,
write('Eligible for loan').
eligible_for_loan(Age, _) :-
Age < 18,
write('Not eligible (under 18)').
eligible_for_loan(_, CreditScore) :-
CreditScore < 700,
write('Not eligible (poor credit score)').

Here:

 If Age >= 18 and CreditScore >= 700, the person is eligible for
a loan, and after printing the message, the cut ensures no other rules
are checked.
 If the person is under 18, Prolog immediately concludes they are not
eligible based on age and does not attempt to check their credit score.

Queries:

prolog

?- eligible_for_loan(25, 750).
Eligible for loan.

?- eligible_for_loan(17, 750).
Not eligible (under 18).

?- eligible_for_loan(30, 650).
Not eligible (poor credit score).

Explanation:

 In the first query, the age and credit score meet the eligibility criteria,
and the cut prevents further backtracking.
 In the second query, the person is under 18, so Prolog doesn’t need to
check the credit score and outputs "Not eligible (under 18)".
 In the third query, the credit score is below the threshold, so Prolog
directly outputs "Not eligible (poor credit score)".

Use Cases of the Cut Operator

 Pruning unnecessary backtracking: If you know that once a particular


rule is true, no other alternatives should be considered, the cut can be
used to improve efficiency.
 Controlling flow: It helps in defining the flow of the program by
committing to one solution and preventing backtracking to other
options.
 Optimizing performance: In cases where Prolog would normally
explore many solutions, using cuts helps to stop the search at a certain
point and return only the best or most relevant solution.

Conclusion
 If-Then-Else in Prolog allows you to make conditional decisions by
using -> for the "then" part and ; for the "else" part. It provides a way
to execute different actions based on conditions, which is useful for
decision-making in Prolog programs.
 The cut operator (!) is a powerful tool to optimize Prolog programs by
preventing backtracking. It commits Prolog to the current choice point
and eliminates the possibility of exploring alternative solutions. The
cut operator is useful for optimizing performance and controlling the
flow of logic in a Prolog program.

These control structures, while relatively simple, provide critical


mechanisms for managing logical flow and improving efficiency in Prolog.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy