SlideShare a Scribd company logo
1 of 37
Download to read offline
Prolog as Part of Artificial Intelligence Course
By
Ahmed Fawzy Gad
Faculty of Computers and Information (FCI)
Menoufia University
Egypt
ahmed.fawzy@ci.menofia.edu.eg
‫المنوفية‬ ‫جامعة‬
‫والمعلومات‬ ‫الحاسبات‬ ‫كلية‬
‫األقسام‬ ‫جميع‬
‫اإلصطناعي‬ ‫الذكاء‬
MENOUFIA UNIVERSITY
FACULTY OF COMPUTERS
AND INFORMATION
ALL DEPARTMENTS
ARTIFICIAL INTELLIGENCE
‫المنوفية‬ ‫جامعة‬
AI Course Pre-requests
 Linear Algebra (e.g. vectors, spaces).
 Probability Theory.
 Set Theory.
 Data Structures (e.g. trees, graphs, stacks).
 Programming Experience (Java).
Extra Knowledge
 Machine Learning.
 Optimization Techniques.
Prolog Course Syllabus
Week 1
 Review about Computer Languages Categories.
o Imperative Languages.
o Declarative Languages.
o Examples.
 Beginner-Professional Java GUI.
 Adding 3 Numbers.
 Pure Imperative Language – Assembly.
 Procedural – Java.
 Declarative.
 Introduction to Prolog.
o Prolog Core Functions.
 Problems Solved by Prolog.
o Examples.
 Students Heights.
 Solutions.
 Family.
 Solutions.
 Manual Prolog Tasks Implementation.
o Examples.
 Students Heights.
 Gender Classification.
 Prolog Implementations.
 SWI-Prolog.
o Installing SWI-Prolog.
 Accessing SWI-Prolog Command-Line.
o Built-in Command-Line Tool.
o CMD.
 SWI-Prolog File Extensions.
 SWI-Prolog Basics.
o Prolog Programs.
 Creating Prolog Program.
 Prolog Clauses.
 Prolog Clauses Types.
o Facts.
o Rules.
o Questions.
 Prolog Clauses Components.
o Head.
o Body.
 Prolog Clauses – Components Mapping.
 Facts.
o Examples.
o Facts General Structure.
 Relations.
 Arguments.
o Facts and Arguments.
 Facts without Arguments.
 Creating Relations.
 Asking Questions/Making Queries.
o Loading Prolog Program.
 GUI.
 Commands.
o Questions Answers.
 True.
 False.
 Error.
 Others.
 Facts with Single Argument.
 Creating Relations.
 Asking Questions/Making Queries.
o Loading Prolog Program.
 Program with Multiple Facts of Same Relation.
 Creating Relations.
 Asking Questions/Making Queries.
o Loading Prolog Program.
 Program with Multiple Relations.
 Creating Relations.
 Asking Questions/Making Queries.
o Loading Prolog Program.
Week 2
 Miscellaneous Topics.
o Programs with Same Relation Name and Arguments Number.
o Prolog Question Goals.
 Question with Single Goal.
 Question with Multiple Goals.
o Contiguous Relations.
o Loading Prolog Program.
 Double-Clicking Prolog Program.
 Built-in Tool GUI.
 Commands.
 Consult.
 consult Alias.
 Load a Program in the CWD.
o Returning the SWI-Prolog CWD.
o Change SWI-Prolog CWD.
 cd.
 working_directory.
 Prolog Terms.
o What are the Prolog Terms?
o Constants.
 Atoms.
 Atom Contents.
 Wrong Atoms.
 Numbers.
o Variables.
 Variables Naming.
 Wrong variables.
o Compound Terms.
 Automatic Backtracking.
o Traditional Single Relation Question.
o Prolog Questions Answers – Others.
 Backtracking with single answer satisfying the goal.
 Backtracking with multiple answers satisfying the goal.
 Automatic Backtracking Definition.
 Facts with Multiple Arguments.
o Family Tree Problem.
 Check Solvability using Prolog.
o Creating Relations.
 Select Appropriate Clause Type.
 Appropriate Relations.
 Appropriate Number of Arguments.
o Asking Questions.
 Traditional Questions – Atoms.
 Parent-Child Combinations – Omitting Print – Special Variable.
 Advanced Questions – Variables.
 Questions Solutions.
 Solutions Explanation.
o Grandparent.
o Siblings.
o Cousins.
 Prolog Predicates.
o Predicate Structure.
o Cousins Predicate.
 Printing Message.
 write.
 print.
 New Line.
 nl.
o Grandparent Predicate.
o Siblings Predicate.
 Prolog Structure with Predicates.
 Family Tree Print Drawback.
o Modified Predicates.
 Siblings.
 Static Solution.
 Dynamic Solution.
 Cousins.
o Complete Family Tree Code with Predicates.
Week 3
 Rules
 Prolog Comparison Operators
 Math in Prolog
 Prolog Arithmetic Operations
 Mathematical Predicates
 Trigonometry Predicates
****Week 1****
Review about Computer Languages Categories
There are different categories of computer languages and each category has its own
characteristics. They can be categorized as follows:
 Imperative Programming.
o Procedural Programming.
o Object-Oriented Programming.
 Declarative Programming.
o Functional Programming.
o Logic Programming.
Imperative Programming
In imperative programing, the programmer gives the computer the detailed steps that it can
follow from receiving the input until generating the output. It uses an imperative style where the
programmer gives commands and the computer just executes these commands and return the
results to the programmer and no more. The programmer gives the computer orders in the form
of instructions that have no more simplifications. I don`t know anything about how to find the
required result and you should tell me what I can do in details to find the result.
Declarative Programming
In declarative programming, the programmer just tells the computer the required results without
describing how to get these results. The language itself has its logic to determine how to get the
results without intervention of the programmer. It knows everything including the sequence of
execution. Just declare the required output and I know how to reach that output using my internal
logic.
Examples to understand the difference between imperative and declarative
programming
Example 1:
Imperative and declarative programming are like dealing with a beginner and a professional.
When you want to do a task like creating a Java GUI, you need to give the Java beginner an order
to do the task in addition to explaining how to do that task step-by-step like:
 Which IDE to use?
 How to create a JFrame?
 How to add a JButton?
 How to create an action? and so on.
The beginner have no experience on how to create a Java GUI.
But you can give an order to the professional to do the task without further details. The
professional have much experience helping to do the task.
Example 2:
The most pure imperative language is Assembly because the computer knows nothing and take
all commands from the programmer.
Example to add two 3 using Assembly:
mov eax, 15: Move 15 into the EAX register.
mov ebx, 20: Move 20 into the EBX register.
add eax, ebx: Add the EAX and EBX then store the results in EAX.
add eax, 5: Add the 5 to EAX then store the results in EAX.
In the previous example, the programmer told the computer how to the task in details from
storing the data into registers to adding the results.
Most of the recent languages like Java, C, C++, Python, and PHP are imperative but not pure
imperative. They can be specifically called procedural.
In procedural programming, the computer knows how to do some tasks and can do it without
waiting for the programmer orders.
The programmer can gives the computer some abstract orders in addition to specifying the
sequence in which the commands are to be executed.
So procedural programming is imperative but not pure imperative.
Imperative – Procedural
 int arr_sum = 0;
 int [] num_arr = {15, 20, 5};
 for(int i=0; i<num_arr.length; i++){
o arr_sum + = num_arr[i];
 }
Note that the previous code is not pure imperative because the computer knows how to do some
operations on its own like storing the data in memory automatically. So it can be said procedural
because the programmer decides the sequence of execution.
Declarative
 sum(15 20 5).
This is a very simple task to do in declarative programming languages.
MySQL may be regarded a declarative language.
One can say that in Java, there is an already existing method to do the sum. So why Java is not a
declarative language?
This is because behind the scenes, there is an actual implementation for the sum() in Java that go
into details of creating an array, looping through it, and summing the results.
But in declarative there is no way to go into these details.
Also never forget that the correct way of programming is the manual implementation of programs
step-by-step and the methods are just existing for making the life easier.
Introduction to Prolog
Prolog is a logic programing language which is a branch from the declarative programming
languages. Prolog stands for PROgramming in LOGic. Prolog was developed in 1972.
As being a declarative language, Prolog doesn`t wait for the programmer to tell it how to do tasks
but it actually knows how to do tasks by itself.
Prolog Core Functions
Prolog differs from usual programming languages because Prolog is centered around some basic
mechanisms like:
 Pattern Matching.
 Tree-based Data Structuring.
 Automatic Backtracking.
Problems Solved by Prolog
Prolog is suitable for problems that can be solved logically including objects, specifically
structured objects that can be represented in a structured or hierarchical way, and relationships
among them. So whenever the problem is formulated with objects it can be solved using Prolog.
A problem consisting of three persons A, B, and C with each person has three properties (eating,
working, sleeping) is a typical problem solved by Prolog to find the relation among them like A
and B eat the same food or work in the same place.
Prolog programming consists of defining relations and creating queries about the relations.
Generally, Prolog is suitable for AI programming but not numerical programming.
Examples
Example 1:
Height of a group of students:
 Salah`s height is 1.7 meters.
 Magdy`s height is 1.5 meters.
 Ramy`s height is 1.6 meters.
 Gamal`s height is 1.55 meters.
 Maher`s height is 1.4 meters.
 Sami`s height is 1.5 meters.
What are the possible student's orders in the class for a good vision?
What is the best possible student's order in the class for a good vision?
Example 2:
 Ahmed is the father of Mohamed.
 Mohamed is the brother of Sami.
 Sami is the friend of Maher.
 Maher is the cousin of Maged.
Can Mohamed and Maged be relatives or friends?
Manual Prolog Tasks Implementation
What can be done using Prolog can be created using the normal programming languages like Java
and C++. So using, say Java, you can do the same tasks performed using Prolog. But it will add
more complexity.
For the classroom example, it can be implemented easily in Java.
The required steps to do the task in Java are:
 Read the data.
 Loop through it.
 Compare heights.
 Order heights in ascending order.
Another example show that some Prolog problems can be implemented easily manually.
 Ahmed is male.
 Dina is female.
 Mohamed is male.
 Samir is male.
 Maha is female.
A command in Prolog can be as follows:
male(ahmed).
Prolog will print true if ahmed is male and false if ahmed is female.
But using Java, you are required to do all of these tasks:
 Read the data.
 Loop through it.
 Check if the name is "ahmed".
 After reaching ahmed, return its gender.
 If the gender of ahmed is male print true, otherwise print false.
You can find that the previous task is trivial to implement in Java without using Prolog. A single
database query can fetch the gender of the name ahmed. Yes, you are right that this task is very
simple to implement manually in Java without using Prolog but there are other queries that can`t
be created using just a simple database queries that we can handle later.
Prolog Implementations
Prolog was firstly developed in 1972.
But there was a problem in Prolog. Prolog was not supporting a large number of applications. To
address this problem, some implementations was released for Prolog.
Of these implementations:
 SWI-Prolog
 GNU-Prolog
 YAP-Prolog
Because each implementation have a different syntax, there was a problem in the language
portability [1].
[1] Wielemaker, Jan, and Vítor Santos Costa. "On the portability of prolog applications."
International Symposium on Practical Aspects of Declarative Languages. Springer Berlin
Heidelberg, 2011.
SWI-Prolog
The Prolog implementation we will use in the course is the SWI-Prolog.
Reasons for using the SWI-Prolog are:
 Cross-platform.
 Free.
 Support for GUI via XPCE.
 Having an interface to C and Java.
SWI-Prolog was developed in 1987 by its original author Jan Wielemaker and implemented based
on C and Prolog.
The SWI-Prolog site is http://www.swi-prolog.org.
Installing SWI-Prolog
The first step before using a language is to prepare the required environment for that language.
For Java, JDE is to be installed.
Also for SWI-Prolog, its environment must be installed.
The SWI-Prolog can be downloaded from http://www.swi-prolog.org/download.html.
It can be installed easily.
After successful installation, the language can be used via its command-line.
Accessing SWI-Prolog Command-Line
In Windows, there are two ways of accessing the SWI-Prolog command-line:
1. Using the built-in command-line tool swipl-win.exe.
2. Using Windows CMD tool swipl.exe.
Calling SWI-Prolog from the built-in command-line swipl-win.exe tool
SWI-Prolog can be called from its built-in command-line tool by just opening the swipl-win.exe
program.
Calling SWI-Prolog from Windows CMD swipl.exe tool
It can also get called from CMD using its swipl.exe program.
So by changing the directory to the SWI-Prolog installation directory, e.g. C:Program
Filesswiplbin, we can enter the swipl command in CMD and the swipl.exe will be called and runs
the SWI-Prolog.
C:> "C:Program Filesswiplbinswipl"
OR
C:> cd "C:Program Filesswiplbin"
C:> swipl
To avoid changing the directory or even typing each time the SWI-Prolog is called, we can save
the SWI-Prolog installation directory in the PATH system/user environment variable.
The command prompt of the SWI-Prolog is ?-.
SWI-Prolog File Extensions
For every computer language, there is a very important thing to know about it before typing code
which is the file extension in which the code will be written.
For example, Java has extensions like .java and .class. C++ extensions are like .cpp, .cc, .h, and
.hpp.
Also Prolog will have its own extensions. The main file extension for SWI-Prolog is .pl.
Due to the confliction with that extension with Perl which have also the .pl extension, another
extension is supported for SWI-Prolog which is .pro.
To be able to use the alternative extension, .pro, the registry key must be modified. The key can
be either of those:
 HKEY_CURRENT_USER/Software/SWI/Prolog/fileExtension.
 HKEY_LOCAL_MACHINE/Software/SWI/Prolog/fileExtension.
So if there is no conflict with other extensions, it is preferred to use the .pl extension.
If there is conflict, use the .pro extension.
SWI-Prolog Basics
A very important note when learning Prolog is to remember that Prolog is different from normal
programming languages we previously used.
Prolog solves logical problems involving objects and the goal is to create relations between them
and asking questions (making queries) about these relations.
There are a number of concepts in Prolog that may differ from what we learned before.
Prolog Programs.
Relations are stored into a Prolog program. The Prolog program is just a simple text file with the
Prolog extension .pl.
The Prolog program is not similar to the regular programs and can also be called
 Database
 Knowledgebase.
So the first step before creating relations is to create the relations container that holds these
relations which is the Prolog program then open it in the SWI-Prolog editor. The file can be created
as follows:
1. Open the SWI-Prolog command-line.
2. Click File menu and then New menu item.
3. Enter the Prolog program name with the extension .pl.
4. Finally save the file and it will be opened automatically and ready for receiving relations.
Another way to create the Prolog program is just creating a text file but with the .pl extension.
Before writing relations inside the Prolog program it will be nice to know that the Prolog program
consists of Prolog clauses and the relations are included within these clauses.
Each clause is terminated with a full stop.
There are three Prolog clauses:
1. Facts: Facts declare things that are always unconditionally true.
2. Rules: Rules declare things that are true depending on a given condition.
3. Questions: The user uses question to ask the program what things are true.
Generally, Prolog clauses consists of two parts:
1. Head:
2. Body: Prolog clause body is a list of goals separated by commas.
After knowing the types of Prolog clauses and the parts of the clause in general, next is to combine
each Prolog clause type with the components that it have.
1. Facts are clauses with a head and an empty body.
2. Rules are clauses with a head and a non-empty body.
3. Questions are clauses with only a body.
Relations won`t be defined inside all of these three clauses but within two types only.
Relations can be defined using:
1. Facts.
2. Rules.
Facts
Facts define things that are unconditionally true. Examples of facts:
 The sun rises from the east.
 For a person named Ahmed Mohamed, saying that parent of Ahmed is Mohamed.
 Water boils at 100 degrees Celsius.
 Humans die when the heart stops.
 Ahmed is male.
Prolog facts are clauses with a head and an empty body used for defining Prolog relations.
The fact is just a tuple consisting of N arguments of that form:
<relation-name>(<argument1>, <argument2>, ..., <argumentN>).
Where N can be any non-negative integer (0, 1, 2, …).
Fact syntax consists of three parts:
1. Relation Name
2. List of Arguments
3. Full Stop
But note that the name of the relations and the arguments must start with a lowercase letter.
A tuple in computer programming refers to an ordered set of values. These values are separated
using a comma.
For each relation, specify the facts as n-tuples of objects that satisfy that relation.
Facts can be:
1. Facts without arguments.
2. Facts with arguments.
Facts without Arguments
The fact in this case is just the relation name.
Examples:
sunny.
So write that fact inside the Prolog program .pl file, save the file, and close it.
Note:
Now, relations are written into facts. Facts are clauses. Clauses are written into Prolog
programs.
After creating relations with facts, we did half of the job. The second half is to make
questions/queries about such relations.
The questions/queries are asked via the SWI-Prolog command-line by asking a question and SWI-
Prolog answers these questions.
To be able to ask a question/query, the SWI-Prolog must be in the query mode. The query mode
is indicated using the ?- command prompt.
Before making the query/question about a relation inside a SWI-Prolog program, it is required to
load the program.
The program is loaded in SWI-Prolog using two ways:
 GUI: File>Consult then select the Prolog program.
 Command: Using the consult('<file-path>') command or its abbreviation ['<file-path>'].
After successfully loading the SWI-Prolog program, next is to ask questions.
The questions will be asked by entering the relation name inside the fact.
For example:
?- sunny.
Because the question is a Prolog clause, it must be terminated by a full stop. Don`t forget that.
Questions Answers
Answers to Prolog questions can be:
 True.
 False.
 Error.
 Others.
Usually, the SWI-Prolog responds by either a true or false.
For facts without arguments, if the relation under query was found, the Prolog returns true. If the
relation was not found, Prolog will gives an error.
It will return false for facts with arguments.
Facts with Arguments
Facts can be more advanced than just a relation name and can also include arguments. We will
start by facts with a single argument.
For example, we can create a fact with a relation named male with one argument which is the
person name.
male(<personName>).
But make sure that the argument begins with a lowercase letter and capitalize the first letter of
words other than the first word if the name consists of multiple words.
So the fact with a relation name male and one arguments will be like this:
male(ahmed).
This fact says that "ahmed is male".
After creating that fact, next is to save the Prolog program and load the program inside Prolog to
make questions. Yes the program was loaded earlier but to apply the modifications the program
must be loaded again. The questions can be like:
?- male(ahmed).
The SWI-Prolog will search the program for a relation named 'male'. If it was found it will search
for an argument named 'ahmed'. If both the relation and the argument were found, Prolog will
return true.
If the argument was not found, Prolog will return false.
If the relation was not found, Prolog will gives an error. Remember that.
For example, try to make questions with arguments that doesn`t exist in the program like:
?- male(mohamed).
You will notice that the Prolog answers with false meaning that it can`t find a fact that says
"mohamed is male".
Program with Multiple Facts of Same Relation
Try to add multiple facts of the same relation male like that:
male(mohamed).
male(ali).
male(samir).
male(khalid).
Then save and load the program to ask questions (make queries) like:
?- male(ahmed).
?- male(ali).
?- male(sameh).
Program with Multiple Relations
Like creating the previous relation named male, we can easily create another relation named
female.
female(sara).
female(ola).
female(mai).
female(gehad).
female(magda).
After entering these relations into the program, next is to save and load the program after
modifications.
After successful loading, try to make questions:
?- male(ola).
?- female(ahmed).
?- male(marwa).
?- male(mohamed).
?- female(gehad).
Comments in Prolog.
As regular computer languages, Prolog has comments. Comments in Prolog can be:
 Single-line: %.
 Multiple-lines: /* … */.
****Week 2****
Miscellaneous Topics
Programs with Same Relation Name and Arguments Number
Prolog can`t load more than one program if they have the same relation with the same number
of arguments. Program will accept to load programs matched in the relation name but with
different arguments like male(ahmed).and male(ahmed, Mohamed).
program3
male(ahmed).
Error
program1
male(ahmed).
program4
male(ahmed, mohamed).
program2
male(mohamed).
Prolog Question Goal
Prolog questions consists of one or more goal that must be satisfied.
Question with Single Goal
Prolog questions can have just a single goal to be satisfied.
For example,
?- male(ahmed).
This question has a single goal to be satisfied which is to find a male named ahmed.
When the answer to the question is positive (e.g. true) we say that the goal was satisfiable. If the
answer was negative (e.g. false) we say that the goal was unsatisfiable.
Question with Multiple Goals
Prolog questions can have more than one goal to be satisfied separated by comma ,.
?- goal1, goal2, goal3, …, goalN.
All of these goal must be satisfied in order for the answer to be positive. It is similar to the AND
operation.
For example:
?- male(ahmed), male(mohamed).
?- male(ahmed), female(ola).
This question has two goals to be satisfied. If at least one goal was not satisfied the question will
return false. The question will return positive answer if and only if all goals are satisfiable.
Contiguous Relations
Clauses of the same relations must be contiguous in the Prolog program. Prolog will return an
error when trying to load the following program.
male(ahmed).
male(mohamed).
female(mona).
male(ali).
The reason is that the clauses of the male relation are not contiguous and separated by another
relation named female.
The following program is correct:
male(ahmed).
male(mohamed).
male(ali).
female(mona).
Loading Prolog Program
Prolog program can be loaded in multiple ways.
Double-Clicking Prolog Program
The easiest and most intuitive way is by double-clicking the Prolog program. It will automatically
open the SWI-Prolog built-in tool with the program already loaded.
Built-in Tool GUI
Using the GUI of the swipl-win tool we can load a Prolog program using the Consult option in the
File menu.
Commands
The previous two ways to load a Prolog program can work with the SWI-Prolog swipl-win built-in
tool but can`t work with Windows CMD.
Loading a Prolog program via CMD will be done using commands.
consult
Using the consult Prolog command we can easily load a Prolog program. That command accepts
the Prolog program path as an argument as follows:
?- consult('PATH').
For example:
?- consult('C:/Users/Dell/Documents/Prolog/test2').
?- consult('C:/Users/Dell/Documents/Prolog/test2.pl').
The extension can be omitted from the command because it is implicitly known as .pl.
consult Alias []
A shortcut to load a program using a command by adding the Prolog program path between two
square brackets [] as follows:
?- ['PATH'].
This does the same job as the consult command.
For example:
?- ['C:/Users/Dell/Documents/Prolog/test2'].
?- ['C:/Users/Dell/Documents/Prolog/test2.pl'].
Loading a Program in the CWD.
Is it required to type the program path each time it is loaded? The answer is no.
Prolog swipl-win tool is much like CMD. It has a current path like CMD.
In CMD, to load a tool located in a different path than the existing path then the complete tool
path or directory must be inserted.
But if the tool was located in the current working directory (CWD) of CMD then just the tool name
can be inserted.
swipl-win has a similar behavior. If the Prolog program was located in the CWD in which the tool
exists then no need to write the complete path or directory. But if the file was located in a
different path than the path at which the tool exist then the path must be inserted.
Returning the SWI-Prolog CWD.
But how to know the current path of the swipl-win tool?
This is via the pwd. command. PWD is short for Current Working Directory.
?- pwd.
After knowing the current directory of the swipl-win tool we can decide how to load the Prolog
program.
If the Prolog program was in the current path then just the Prolog program name is required to
load the program. For example:
?- consult(test2).
?- [test2].
Normally if the Prolog program was in different location then there are two ways to load it.
The first is to type its path as an argument to consult or [] as explained earlier.
Change SWI-Prolog Current Directory
The second is to change the current path of the SWI-Prolog.
The path can be changed using the cd command with the following signature:
?- cd(NEW_PATH).
For example:
?- cd('C:UsersDellDocumentstemp_folder').
Another command that can change the directory is called working_directory with the
following signature:
?- working_directory(OLD, NEW).
For example:
?- working_directory(CWD, C:UsersDellDocumentstemp_folder').
Prolog Terms
Previously we creates two relations named male and female inside a fact with a single
argument. After creating the relations next was to ask questions. The questions asked was of that
form:
Is the person <personName> is male?
Is the person <personName> is female?
There are other questions to be asked like:
 What are the persons that are male?
 What are the persons that are female?
The previous questions are very simple and doesn`t reflect the intelligence in Prolog. It is just like
searching a database. Is it possible to use a language like Prolog to just create search in a database
while there are other languages like MySQL that can do that tasks better than Prolog?
Prolog is not restricted to do operations like searching in a database but as more arguments and
more relations existing in the Prolog program there will be more tasks that are not just searching
a database.
To be able to create questions of that form, we need to know about Prolog terms.
What are the Prolog Terms?
All Prolog data structures are called terms. So any way in Prolog used to store data are called
terms.
Prolog has three main terms:
1. Constants.
2. Variables.
3. Complex or Compound Terms.
Constants include two terms:
1. Atoms.
2. Numbers.
Constants
Constant is something that never changes.
Constant in Prolog can be either atoms or numbers.
Atoms
Atoms are term type we used in previous examples.
Atoms are like strings in Java and C++.
An atom is a string of characters made up of:
 Uppercase letters (A-Z).
 Lowercase letters (a-z).
 Digits (0-9).
 Underscore (_).
Important note: Atoms must start with a lowercase letter.
Terms
Constants
Atoms
Numbers
Variables
Compound
Terms
Examples:
 ahmedMohamed
 ahmed_mohamed
 way2home
Regular atom can`t:
 Contain spaces.
 Contain special characters like !, @, %, $, #, and so on.
 Start with an uppercase letter.
So the following are invalid atoms:
 Ahmed
 #OfUsers
 ahmed mohamed
But an atom can do all of those if it was enclosed between single quotes.
So to make the previous atoms valid, enclose them between single quotes ' ':
 'Ahmed'
 '#Users'
 'ahmed mohamed'
Generally speaking, anything data enclosed between single quotes is an atom.
Numbers
Numbers in any computer language can be either:
 Integer (…, -3, -2, -1, 0, 1, 2, 3, …).
 Floating-point like π, 728.1312, -131.63.
It is not common to use floating-point numbers in Prolog but they are available. This is a proof
that Prolog is not intended for numerical programming.
Variables
A variable is a string of characters made up of:
 Uppercase letters (A-Z).
 Lowercase letters (a-z).
 Digits (0-9).
 Underscore (_).
Important note: Variables must start with an uppercase letter or underscore and can`t be
enclosed between single or double quotes.
Remember: Whenever you see a string starting with an uppercase letter, it will be a variable. If it
starts by a lowercase letter, it is an atom. If it was enclosed between single quotes it is also an
atom.
Anonymous Variable
Variable can be just an underscore (_) but it is a special variable in Prolog called anonymous
variable.
Examples:
 X
 _X
 X1
 X_Y
Variables can`t:
 Contain spaces.
 Contain special characters like !, @, %, $, #, and so on.
 Start with a lowercase letter.
So the following are invalid variables:
 x
 #OfUsers
 X Y
Automatic Backtracking
After having knowledge about what are the terms (specially variables) in Prolog, we can start
making new questions to Prolog rather than the simple ones discussed previously.
Previously we asked questions like:
Is ahmed is male?
Is mona is female?
These questions are written as follows in Prolog:
male(ahmed).
female(mona).
Now we will ask questions in that form:
What are the names of males?
What are the names of females?
These questions are written as follows in Prolog:
male(X).
female(X).
Prolog Questions Answers – Others
The difference between these two types of questions is using variables rather than atoms.
We have previously said that Prolog answers can be true, false, error, or others and knew when
the answer can be true, false, and error.
For example, when asking that question male(ahmed).. The answer can be either true, false, or
error. True if there is a male called ahmed, false if no male called ahmed was found in the
knowledgebase, and error if the relation name or the number of arguments were not matched
any fact in the program.
Other answers than these three answers can be returned for question like male(X).. It can
return true, false, or error as discussed previously and can also return other answers which is the
name of males in the knowledgebase.
Backtracking with single answer satisfying the goal
When asking that question male(X)., Prolog searches the knowledgebase for all males and the
first male found will be returned into the variable X.
Because there is only one male in the database, Prolog just returns that male into the variable X
and terminates the execution of the question.
The effect of automatic backtracking will appear when there are multiple relations satisfying the
goal of the question.
Backtracking with multiple answers satisfying the goal
When there are multiple relations satisfying the goal of the question the effect of automatic
backtracking appears.
Because there may be multiple males in the dataset, Prolog provides a way to get the alternative
males which is called automatic backtracking.
Automatic backtracking in Prolog is to know the alternative solutions that satisfy a given relation.
Alternative solutions can be found using semicolon ;.
For each semicolon ; entered, a new solution will be returned into the variable X until reaching
the end of the list of solutions.
Example:
male(X).
X = ahmed ;
X = mohamed ;
X = ali ;
X = samir ;
X = khalid.
Facts with Multiple Arguments
Suppose that it is required to define the following family tree using a Prolog program.
Check Solvability using Prolog
Because the problem can be formulated as a hierarchy like a tree it can be solved in Prolog.
Major steps to deal with a problem in Prolog are:
1. Creating Relations.
2. Asking Questions.
Creating Relations
Before creating relations, it is required to decide the type of Prolog clauses that is convenient with
the problem to hold the relations.
Select Appropriate Clause Type
From the problem nature, it is clear that the problem presents things that are always true. So the
type of Prolog clauses to use is fact.
After determining what type of Prolog clauses to be used, it is required to determine the parts of
the facts. Remember that facts consist of a relation and a number of arguments.
So we must define the following:
 Relation name.
 Number of arguments.
Appropriate Relations
Because the tree presents a child-parent relationship, good relations to be used are:
 Child.
 Parent.
Appropriate Number of Arguments
Suppose we selected the parent relationship to model that problem, next is to determine the
number of arguments it should take.
The parent relation maps a parent to its child, so there should be two arguments to represent the
following:
1. Parent name.
2. Child name.
After determining the clause type, relation name, and number of arguments, we can write the
general form of the fact as follows:
parent(<parentName>, <childName>).
At first, it is fine to list all the parent-child facts as statements in English and map each statement
to a fact.
Fact Statement SWI-Prolog Representation
Mohamed is parent of Ahmed. parent(mohamed,ahmed).
Ahmed is parent of Kamal. parent(ahmed, kamal).
Ahmed is parent of Sabry. parent(ahmed, sabry).
Ahmed is parent of Mona. parent(ahmed, mona).
Kamal is parent of Maher. parent(kamal, maher).
Sabry is parent of Hala. parent(sabry, hala).
Sabry is parent of Ghada. parent(sabry, ghada).
The complete SWI-Prolog facts for the parent relation are as follows:
parent(mohamed, ahmed).
parent(ahmed, kamal).
parent(ahmed, sabry).
parent(ahmed, mona).
parent(kamal, maher).
parent(sabry, hala).
parent(sabry, ghada).
Note: The relation name in addition to the arguments start by lowercase letters.
Asking Questions
After saving the Prolog program and loading it we come to the step of asking questions and
making queries.
We want to ask two types of questions:
1. Traditional Questions – Atoms.
2. Advanced Questions – Variables.
Traditional Questions – Atoms
We will start by the traditional questions in which the arguments are constants (atoms) then move
to more advanced questions using variables.
Examples of questions and queries:
parent(ahmed, mona).
parent(kamal, mahar).
parent(sabry, magdy).
parent(ghada, sabry).
As regular, when a question is asked, Prolog searches for the question relation entered which in
this case parent with the same number of arguments entered which in this example 2.
If any of these conditions not matched, an error will be given. If there was a relation called parent
accepting two arguments then matching take place.
If the question arguments matched arguments of a fact in the program then Prolog returns true.
If the question arguments not matched any of the facts arguments in the program, then Prolog
will return false.
The previous questions were of this form:
Is the parent <parentName> has a child <childName>?
For example, the question parent(ahmed, mona). asks Prolog if there is a parent named ahmed
has a child named mona.
Advanced Questions – Variables
As we did earlier, using variables it is possible to make other forms of questions that Prolog can
answer like:
1. What are the children of the parent <parentName>?
2. What is the parent of the child <childName>?
3. What are the parent-children combinations?
4. What is the grandparent of the child <childName>?
5. What are the siblings of the child <childName>? (Siblings = Brothers + Sisters).
6. What are the cousins of the child <childName>?
The previous examples shows some bit complex operations that can`t be implemented easily in
programming languages like Java even if just a single relation with just two arguments are used.
This proves that Prolog is the best option for such applications.
Note: Set the argument to a variable wherever the argument constant value is missing.
The way to do the previous questions is as follows:
# Question Statement
1 What are the children of ahmed?
2 What is the parent of ahmed?
3 What are the parent-child combinations?
4 What is the grandparent of kamal?
5 What are the siblings of mona?
6 What are the cousins of maher?
The way to do the previous questions is as follows:
# Question Statement SWI-Prolog Representation
1 What are the children of ahmed? parent(ahmed, X).
2 What is the parent of ahmed? parent(X, ahmed).
3 What are the parent-child combinations? parent(X, Y).
4 What is the grandparent of kamal? parent(X, kamal), parent(Y, X).
5 What are the siblings of mona? parent(X, mona), parent(X, Y).
6 What are the cousins of maher? parent(A, maher), parent(B, A) , parent(B, C) ,
parent(C, Cousins).
Solutions Explanation
The first three questions are easily understood. Wherever the value of the argument is unknown,
use a variable instead. The first question gives the parent name value but not the child name. So
set the child argument to a variable. The second question gives the child name value but not the
parent name. So set the parent argument to a variable. The third question doesn`t give neither
the parent name value nor the child name. So set both the parent and child arguments to
variables.
Parent-Child Combinations – Omitting Print – Special Variable
When issuing this command in Prolog:
parent(X, Y).
Prolog prints both the parent name and child name.
If we are interested only in parent names then we can omit the print of the child name by using
the special variable _.
parent(X, _).
To print only the child name not the parent name:
parent(_, X).
Deeper explanation will be for the last three questions.
Note: When the question can`t be answered by just using a single relation think of using multiple
relations to find the solution.
Grandparent
There is no relation named grandparent and thus Prolog can`t answer the question what is the
grandparent of?
Prolog only knows about the parent relation and thus it can answer question what is the parent
of?.
So how to use the parent relation to get the grandparent?
Because a grandparent is the parent of a parent, the grandparent relationship can be divided into
two parent relations.
So to find the parent of kamal, just find the parent of kamal then the parent of the parent of
kamal.
How to make two consecutive questions in Prolog.
Ask the first question but replace the full stop in it by a comma then ask the second question
terminated normally by a full stop.
To find the answer of the question 'What is the grandparent of kamal?' we can create two parent
relations as follows:
1. The first question will get the parent of kamal in the variable X.
2. Because the parent of kamal was returned into the variable X, so to know the parent of
the parent of kamal we need a second question that asks for the parent of the variable X.
grandparent of kamal = parent of parent of kamal.
parent of kamal = X.
parent of parent of kamal = parent of X.
parent of X = Y.
This is how to do it in Prolog:
parent(X, kamal), parent(Y, X).
Siblings
Because there is no relation to find the siblings relation and we just can find the parent relation,
we have to divide the siblings relation into a number of parent relations.
As siblings are the other children of a parent, so to find the siblings of someone, we have to find
the parent of that one and then find the children of the parent.
The answer of the question 'What are the aiblings of mona?' will be answered using two parent
relations:
 First one finds the parent of mona and return it into a variable X.
 Second relation will find the children of the parent of mona and return it into a variable
Y.
Siblings of mona = other children of mona `s parent.
mona `s parent = X.
other children of mona `s parent = other children of X.
children of X = Y.
This is how to do it in Prolog:
parent(X, mona), parent(X, Y).
Cousins
Because there is no relation to find the cousins, we have to divide it into a number of parent
relations.
Cousins are the children of someone`s siblings.
So to find the cousins of someone, we need to find the grandparent of that one, then find the
children of that grandparent and finally find the children of each child.
The answer of the question 'What are the aiblings of maher?' will be answered using three parent
relations:
 Finds the parent of maher and return it into a variable c.
 Find the parent of maher`s parent and return it into a variable B.
 Find the children of the parent of maher`s parent and return it into a variable C.
 Find the children of the children of the parent of maher`s parent and return it into a
variable Cousins.
cousins of maher = the children of the children of the parent of maher`s parent.
maher`s parent = A.
cousins of maher are the children of the children of the parent of A.
parent of A = B.
cousins of maher are the children of the children of B.
children of B = C.
cousins of maher are the children of C.
children of C = Cousins.
cousins of maher = Cousins.
This is how to do it in Prolog:
parent(A, maher), parent(B, A) , parent(B, C) , parent(C, Cousins).
Prolog Predicates
Each time a cousin relationship is to be found in Prolog we have to enter a long command in the
command-line like that:
parent(A, <personName>), parent(B, A) , parent(B, C) , parent(C, Cousins).
This is tiresome specially for a long number of goals to be entered in the command-line.
We can make use of a new concept in Prolog called predicates to overcome this problem.
Predicates in Prolog are similar to functions and methods in regular programming languages.
So we can write a predicate in Prolog that holds all of work and just access it by a simple command.
For example, rather than writing this long question to find the cousin relationship, we can create
a predicate called cousins and put all work inside it.
Predicate Structure
Predicate consists of a number of clauses separated by commas. The last clause of the predicate
is terminated by a full stop.
Like having input arguments for the functions and methods, Prolog predicate can have a number
of arguments and variables as its input.
The general structure of a Prolog predicate is as follows:
predicate_name(listOfArgumentsAndVariables):-
clause1,
clause2,
clause3,
.
.
.
clauseN.
cousins Predicate
For example, we can create a predicate as a shortcut for finding the cousin relation as follows:
cousins(PersonName):-
parent(A, PersonName),
parent(B, A),
parent(B, C),
parent(C, Cousins),
write('Cousins of '),
write(PersonName),
write(' are '),
write(Cousins).
The cousins predicate accepts the person name in the variable PersonName and prints to find
its cousins.
Note that the cousins predicate uses the parent relation but the parent relation can be
defined before or after the cousins predicate.
Printing Message
parent(A, <personName>), parent(B, A) ,
parent(B, C) , parent(C, Cousins).
cousins(<personName>).
The write(D). clause is used to print the value of the variable D.
write is one of the built-in predicates in Prolog.
Generally, the write() is used to print something on the command-line and the writeln() is
used to print something on the command-line and finally make a new line.
For example:
write('Just a message.').
Similar predicate is print().:
print('Just a message.').
New Line
A new line can be created using the nl. command.
grandparent Predicate
We can create another predicate to find the grandparent of a person as follows:
grandparent(ChildName):-
parent(Parent, ChildName),
parent(GrandParent, Parent),
write('The parent of '),
write(ChildName),
write(' is '),
write(Parent),
writeln('.'),
write('The parent of '),
write(Parent),
write(' is '),
write(GrandParent),
writeln('.'),
write('So the grandparent of '),
write(ChildName),
write(' is '),
write(GrandParent),
writeln('.').
The grandparent predicate accepts the child name into the variable ChildName and prints its
parent and grandparent names.
siblings Predicate
Finally we can create a siblings predicate to find the siblings of someone`s name passed in the
ChildName variable as follows:
siblings(ChildName):-
parent(Parent, ChildName),
parent(Parent, Siblings),
write(Siblings of '),
write(ChildName),
write(' are '),
write(Siblings).
Prolog Structure with Predicates
After using predicates, we can say that Prolog consists of programs. Programs contains of
predicates. Predicates contains clauses. Clauses can be facts, rules, and questions. Clauses
contains relations which is the goal of Prolog. Questions are created to query such relations.
 Prolog.
 Program.
 Predicates.
 Clauses.
 Relations.
Drawback
When trying to find the siblings of sabry, for example, the result will be:
1. Kamal.
2. Mona.
3. Sabry.
sabry is printed in the result and that means Sabry is a sibling of Sabry which is not true.
So it is more accurate to say that Siblings of sabry are just:
1. Kamal.
2. Mona.
So the question is how to remove sabry from the result.
When analyzing the Siblings predicate, it can be easily found that the list of siblings are returned
into the Siblings variable. That variable will have three values (Kamal, Mona, and Sabry). We
want to remove the sabry value from the list of values of the Siblings variable.
That can be done in different ways like:
 dif(Siblings, sabry).
 Siblings = sabry.
Siblings
Static Solution
The modified siblings predicate is as follows:
siblings(ChildName):-
parent(Parent, ChildName),
parent(Parent, Siblings),
dif(Siblings, sabry),
write(Siblings of '),
write(ChildName),
write(' are '),
write(Siblings).
Dynamic Solution
To make that dynamic over any siblings we can remove the static value sabry and use the
ChildName variable.
The modified siblings predicate is as follows:
siblings(ChildName):-
parent(Parent, ChildName),
parent(Parent, Siblings),
dif(Siblings, ChildName),
write(Siblings of '),
write(ChildName),
write(' are '),
write(Siblings).
Cousins
The previous procedure can be applied to the cousins predicate to avoid printing the query
person name in the result.
The cousins predicate will be modified as follows:
cousins(PersonName):-
parent(A, PersonName),
parent(B, A),
parent(B, C),
parent(C, Cousins),
dif(Cousins, PersonName),
write('Cousins of '),
write(PersonName),
write(' are '),
write(Cousins).
Complete Family Tree Code with Predicates
The complete program is as follows:
parent(mohamed, ahmed).
parent(ahmed, kamal).
parent(ahmed, sabry).
parent(ahmed, mona).
parent(kamal, maher).
parent(sabry, hala).
parent(sabry, ghada).
cousins(PersonName):-
parent(A, PersonName),
parent(B, A),
parent(B, C),
parent(C, Cousins),
dif(Cousins, PersonName),
write('Cousins of '),
write(PersonName),
write(' are '),
write(Cousins).
grandparent(ChildName):-
parent(Parent, ChildName),
parent(GrandParent, Parent),
write('The parent of '),
write(ChildName),
write(' is '),
write(Parent),
writeln('.'),
write('The parent of '),
write(Parent),
write(' is '),
write(GrandParent),
writeln('.'),
write('So the grandparent of '),
write(ChildName),
write(' is '),
write(GrandParent),
writeln('.').
siblings(ChildName):-
parent(Parent, ChildName),
parent(Parent, Siblings),
dif(Siblings, ChildName),
write('Siblings of '),
write(ChildName),
write(' are '),
write(Siblings).
****Week 3****
Rules
Creating Rule
The statement "student succeeds if the score is more than or equal 50" can`t be inserted into
Prolog as a fact but more appropriately using a rule.
It can be modelled as follows:
?- suceeds(X) :- X >= 50.
This is similar to an IF statement in regular programming languages like Java.
Prolog Comparison Operators
Greater Than >
Less Than <
Greater Than Or Equal >=
Less Than Or Equal =<
Equals =:=
Not Equals ==
Math in Prolog
We have previously said that Prolog doesn`t target numerical applications but works with
problems including objects. This doesn`t prevent the existence of some simple numerical
operations built inside Prolog.
Prolog Arithmetic Operations
Being familiar to Java or C++, you can imagine that Prolog arithmetic operations like addition can
be like that:
?- X = 1 + 2.
Where X is the variable that holds the result of adding 1 and 2. But this is not correct.
There are two assignment operators in Prolog:
1. is
2. =
Explanation of the difference is better explained by an example:
?- X is 1 + 2.
?- X = 1 + 2.
The right solution is what uses the is operator.
The is operator should only be used when performing arithmetic operations on the RHS of the
equation.
Mathematical Predicates
pow(2, 4, X). %2 to the power 4 = 16 and save it into variable X.
X is max(4, 7).
X is min(4, 7).
X is abs(-4).
X is ceiling(3.2).
X is floor(3,2).
X is round(3,2).
integer(3.4). %Returns true if the input is integer and false otherwise.
X is log(4). %Logarithm with the e as the base.
X is log10(49). %Logarithm with 10 as the base.
X is sign(4). %1 if positive, -1 if negative, and 0 if zero.
X is sqrt(4).
Trigonometry Predicates
X is sin(50).
X is cos(50).
X is tan(50).
X is asin(50).
X is acos(50).
X is atan(50).
Miscellaneous Prolog Predicates
ls. List files in current folder.
edit('SWI-Prolog/program/absolute/path/with/or/without/extension'). Edit the SWI-Prolog
program specified by the path.
edit. If the SWI-Prolog program was opened by double-clicking it, it can be edited by just edit.
without specifying the path.
read(prompt): Request input from the user.
nl: Prints new line.
write(message): Prints a message on the screen.
halt(0): Exit Prolog.
Editing SWI-Prolog programs:
 Open the SWI-Prolog then click File>Edit to select the SWI-Prolog progam.
 Use the edit('path'). Command by specifying the SWI-Prolog program name.
 Double-click the SWI-Prolog program and enter edit. without adding the path.
Notes on naming relations:
 The relations have a name that is a noun or a noun phrase. Multiple words in the relation
name are separated by underscore _ and each word starts with a lowercase letter.
 Try to give the relations an unambiguous names and be aware of symmetry in which the
relation name can be read in multiple ways.
 For example, the fact parent(A, B) can be read in two ways:
1. A is parent of B.
2. B is parent of A.
But of the relation was named parent_child there will be no ambiguity because parent_chils(A, B)
means that A is the parent and B is the child.
Also try to give arguments a descriptive name with mixed-case letters. E.g. childName instead of
child_name starting with a lowercase letter like the relation.
Trace the program execution by entering trace. before issuing a command.

More Related Content

What's hot

01 knapsack using backtracking
01 knapsack using backtracking01 knapsack using backtracking
01 knapsack using backtrackingmandlapure
 
Introduction on Prolog - Programming in Logic
Introduction on Prolog - Programming in LogicIntroduction on Prolog - Programming in Logic
Introduction on Prolog - Programming in LogicVishal Tandel
 
Linear regression, costs & gradient descent
Linear regression, costs & gradient descentLinear regression, costs & gradient descent
Linear regression, costs & gradient descentRevanth Kumar
 
Deterministic Finite Automata (DFA)
Deterministic Finite Automata (DFA)Deterministic Finite Automata (DFA)
Deterministic Finite Automata (DFA)Animesh Chaturvedi
 
Lab report for Prolog program in artificial intelligence.
Lab report for Prolog program in artificial intelligence.Lab report for Prolog program in artificial intelligence.
Lab report for Prolog program in artificial intelligence.Alamgir Hossain
 
Syntax directed translation
Syntax directed translationSyntax directed translation
Syntax directed translationAkshaya Arunan
 
Divide and Conquer - Part 1
Divide and Conquer - Part 1Divide and Conquer - Part 1
Divide and Conquer - Part 1Amrinder Arora
 
The Maximum Subarray Problem
The Maximum Subarray ProblemThe Maximum Subarray Problem
The Maximum Subarray ProblemKamran Ashraf
 
Artificial Intelligence 1 Planning In The Real World
Artificial Intelligence 1 Planning In The Real WorldArtificial Intelligence 1 Planning In The Real World
Artificial Intelligence 1 Planning In The Real Worldahmad bassiouny
 
5.3 dynamic programming
5.3 dynamic programming5.3 dynamic programming
5.3 dynamic programmingKrish_ver2
 
Discrete Mathematics Lecture
Discrete Mathematics LectureDiscrete Mathematics Lecture
Discrete Mathematics LectureGenie Rose Santos
 
Prolog Programming : Basics
Prolog Programming : BasicsProlog Programming : Basics
Prolog Programming : BasicsMitul Desai
 
Deep Learning A-Z™: Recurrent Neural Networks (RNN) - The Vanishing Gradient ...
Deep Learning A-Z™: Recurrent Neural Networks (RNN) - The Vanishing Gradient ...Deep Learning A-Z™: Recurrent Neural Networks (RNN) - The Vanishing Gradient ...
Deep Learning A-Z™: Recurrent Neural Networks (RNN) - The Vanishing Gradient ...Kirill Eremenko
 

What's hot (20)

Class ppt intro to r
Class ppt intro to rClass ppt intro to r
Class ppt intro to r
 
01 knapsack using backtracking
01 knapsack using backtracking01 knapsack using backtracking
01 knapsack using backtracking
 
Introduction on Prolog - Programming in Logic
Introduction on Prolog - Programming in LogicIntroduction on Prolog - Programming in Logic
Introduction on Prolog - Programming in Logic
 
Linear regression, costs & gradient descent
Linear regression, costs & gradient descentLinear regression, costs & gradient descent
Linear regression, costs & gradient descent
 
Deterministic Finite Automata (DFA)
Deterministic Finite Automata (DFA)Deterministic Finite Automata (DFA)
Deterministic Finite Automata (DFA)
 
AI: Logic in AI
AI: Logic in AIAI: Logic in AI
AI: Logic in AI
 
Approximation Algorithms
Approximation AlgorithmsApproximation Algorithms
Approximation Algorithms
 
Bert
BertBert
Bert
 
Lab report for Prolog program in artificial intelligence.
Lab report for Prolog program in artificial intelligence.Lab report for Prolog program in artificial intelligence.
Lab report for Prolog program in artificial intelligence.
 
Syntax directed translation
Syntax directed translationSyntax directed translation
Syntax directed translation
 
Divide and Conquer - Part 1
Divide and Conquer - Part 1Divide and Conquer - Part 1
Divide and Conquer - Part 1
 
Dynamic programming
Dynamic programmingDynamic programming
Dynamic programming
 
Propositional Logic and Pridicate logic
Propositional Logic and Pridicate logicPropositional Logic and Pridicate logic
Propositional Logic and Pridicate logic
 
The Maximum Subarray Problem
The Maximum Subarray ProblemThe Maximum Subarray Problem
The Maximum Subarray Problem
 
Artificial Intelligence 1 Planning In The Real World
Artificial Intelligence 1 Planning In The Real WorldArtificial Intelligence 1 Planning In The Real World
Artificial Intelligence 1 Planning In The Real World
 
5.3 dynamic programming
5.3 dynamic programming5.3 dynamic programming
5.3 dynamic programming
 
Discrete Mathematics Lecture
Discrete Mathematics LectureDiscrete Mathematics Lecture
Discrete Mathematics Lecture
 
Ai lab manual
Ai lab manualAi lab manual
Ai lab manual
 
Prolog Programming : Basics
Prolog Programming : BasicsProlog Programming : Basics
Prolog Programming : Basics
 
Deep Learning A-Z™: Recurrent Neural Networks (RNN) - The Vanishing Gradient ...
Deep Learning A-Z™: Recurrent Neural Networks (RNN) - The Vanishing Gradient ...Deep Learning A-Z™: Recurrent Neural Networks (RNN) - The Vanishing Gradient ...
Deep Learning A-Z™: Recurrent Neural Networks (RNN) - The Vanishing Gradient ...
 

Similar to Introduction to Prolog (PROramming in LOGic)

Cis 1403 lab1- the process of programming
Cis 1403 lab1- the process of programmingCis 1403 lab1- the process of programming
Cis 1403 lab1- the process of programmingHamad Odhabi
 
Top interview questions in c
Top interview questions in cTop interview questions in c
Top interview questions in cAvinash Seth
 
Lesson 1 - Introduction to Computer Programming.pptx
Lesson 1 - Introduction to Computer Programming.pptxLesson 1 - Introduction to Computer Programming.pptx
Lesson 1 - Introduction to Computer Programming.pptxNeil Mutia
 
Computer Science Is The Study Of Principals And How The...
Computer Science Is The Study Of Principals And How The...Computer Science Is The Study Of Principals And How The...
Computer Science Is The Study Of Principals And How The...Laura Martin
 
Programming Paradigms
Programming ParadigmsProgramming Paradigms
Programming ParadigmsDirecti Group
 
Designing function families and bundles with java's behaviors parameterisatio...
Designing function families and bundles with java's behaviors parameterisatio...Designing function families and bundles with java's behaviors parameterisatio...
Designing function families and bundles with java's behaviors parameterisatio...Alain Lompo
 
Programming Paradigms
Programming ParadigmsProgramming Paradigms
Programming ParadigmsJaneve George
 
Intro. to prog. c++
Intro. to prog. c++Intro. to prog. c++
Intro. to prog. c++KurdGul
 
Python week 5 2019 2020 for g10 by eng.osama ghandour
Python week 5 2019 2020 for g10 by eng.osama ghandourPython week 5 2019 2020 for g10 by eng.osama ghandour
Python week 5 2019 2020 for g10 by eng.osama ghandourOsama Ghandour Geris
 
Object Oriented programming - Introduction
Object Oriented programming - IntroductionObject Oriented programming - Introduction
Object Oriented programming - IntroductionMadishetty Prathibha
 
Contents Pre-requisites Approximate .docx
   Contents Pre-requisites  Approximate .docx   Contents Pre-requisites  Approximate .docx
Contents Pre-requisites Approximate .docxShiraPrater50
 
Java OOPs Concepts.docx
Java OOPs Concepts.docxJava OOPs Concepts.docx
Java OOPs Concepts.docxFredWauyo
 
Boost Your Base Bootcamp - [Online & Offline] In Bangla
Boost Your Base Bootcamp - [Online & Offline] In BanglaBoost Your Base Bootcamp - [Online & Offline] In Bangla
Boost Your Base Bootcamp - [Online & Offline] In BanglaStack Learner
 
Python week 5 2019-2020 for G10 by Eng.Osama Ghandour.ppt
Python week 5 2019-2020 for G10 by Eng.Osama Ghandour.pptPython week 5 2019-2020 for G10 by Eng.Osama Ghandour.ppt
Python week 5 2019-2020 for G10 by Eng.Osama Ghandour.pptOsama Ghandour Geris
 

Similar to Introduction to Prolog (PROramming in LOGic) (20)

Unit 1
Unit 1Unit 1
Unit 1
 
JAVA
JAVAJAVA
JAVA
 
OOP Java
OOP JavaOOP Java
OOP Java
 
Cis 1403 lab1- the process of programming
Cis 1403 lab1- the process of programmingCis 1403 lab1- the process of programming
Cis 1403 lab1- the process of programming
 
Top interview questions in c
Top interview questions in cTop interview questions in c
Top interview questions in c
 
C++ book
C++ bookC++ book
C++ book
 
Lesson 1 - Introduction to Computer Programming.pptx
Lesson 1 - Introduction to Computer Programming.pptxLesson 1 - Introduction to Computer Programming.pptx
Lesson 1 - Introduction to Computer Programming.pptx
 
Computer Science Is The Study Of Principals And How The...
Computer Science Is The Study Of Principals And How The...Computer Science Is The Study Of Principals And How The...
Computer Science Is The Study Of Principals And How The...
 
Programming Paradigms
Programming ParadigmsProgramming Paradigms
Programming Paradigms
 
Designing function families and bundles with java's behaviors parameterisatio...
Designing function families and bundles with java's behaviors parameterisatio...Designing function families and bundles with java's behaviors parameterisatio...
Designing function families and bundles with java's behaviors parameterisatio...
 
Programming Paradigms
Programming ParadigmsProgramming Paradigms
Programming Paradigms
 
Intro. to prog. c++
Intro. to prog. c++Intro. to prog. c++
Intro. to prog. c++
 
Introductoin to Python.ppt
Introductoin to Python.pptIntroductoin to Python.ppt
Introductoin to Python.ppt
 
Python week 5 2019 2020 for g10 by eng.osama ghandour
Python week 5 2019 2020 for g10 by eng.osama ghandourPython week 5 2019 2020 for g10 by eng.osama ghandour
Python week 5 2019 2020 for g10 by eng.osama ghandour
 
UNIT1-JAVA.pptx
UNIT1-JAVA.pptxUNIT1-JAVA.pptx
UNIT1-JAVA.pptx
 
Object Oriented programming - Introduction
Object Oriented programming - IntroductionObject Oriented programming - Introduction
Object Oriented programming - Introduction
 
Contents Pre-requisites Approximate .docx
   Contents Pre-requisites  Approximate .docx   Contents Pre-requisites  Approximate .docx
Contents Pre-requisites Approximate .docx
 
Java OOPs Concepts.docx
Java OOPs Concepts.docxJava OOPs Concepts.docx
Java OOPs Concepts.docx
 
Boost Your Base Bootcamp - [Online & Offline] In Bangla
Boost Your Base Bootcamp - [Online & Offline] In BanglaBoost Your Base Bootcamp - [Online & Offline] In Bangla
Boost Your Base Bootcamp - [Online & Offline] In Bangla
 
Python week 5 2019-2020 for G10 by Eng.Osama Ghandour.ppt
Python week 5 2019-2020 for G10 by Eng.Osama Ghandour.pptPython week 5 2019-2020 for G10 by Eng.Osama Ghandour.ppt
Python week 5 2019-2020 for G10 by Eng.Osama Ghandour.ppt
 

More from Ahmed Gad

ICEIT'20 Cython for Speeding-up Genetic Algorithm
ICEIT'20 Cython for Speeding-up Genetic AlgorithmICEIT'20 Cython for Speeding-up Genetic Algorithm
ICEIT'20 Cython for Speeding-up Genetic AlgorithmAhmed Gad
 
NumPyCNNAndroid: A Library for Straightforward Implementation of Convolutiona...
NumPyCNNAndroid: A Library for Straightforward Implementation of Convolutiona...NumPyCNNAndroid: A Library for Straightforward Implementation of Convolutiona...
NumPyCNNAndroid: A Library for Straightforward Implementation of Convolutiona...Ahmed Gad
 
Python for Computer Vision - Revision 2nd Edition
Python for Computer Vision - Revision 2nd EditionPython for Computer Vision - Revision 2nd Edition
Python for Computer Vision - Revision 2nd EditionAhmed Gad
 
Multi-Objective Optimization using Non-Dominated Sorting Genetic Algorithm wi...
Multi-Objective Optimization using Non-Dominated Sorting Genetic Algorithm wi...Multi-Objective Optimization using Non-Dominated Sorting Genetic Algorithm wi...
Multi-Objective Optimization using Non-Dominated Sorting Genetic Algorithm wi...Ahmed Gad
 
M.Sc. Thesis - Automatic People Counting in Crowded Scenes
M.Sc. Thesis - Automatic People Counting in Crowded ScenesM.Sc. Thesis - Automatic People Counting in Crowded Scenes
M.Sc. Thesis - Automatic People Counting in Crowded ScenesAhmed Gad
 
Derivation of Convolutional Neural Network from Fully Connected Network Step-...
Derivation of Convolutional Neural Network from Fully Connected Network Step-...Derivation of Convolutional Neural Network from Fully Connected Network Step-...
Derivation of Convolutional Neural Network from Fully Connected Network Step-...Ahmed Gad
 
Introduction to Optimization with Genetic Algorithm (GA)
Introduction to Optimization with Genetic Algorithm (GA)Introduction to Optimization with Genetic Algorithm (GA)
Introduction to Optimization with Genetic Algorithm (GA)Ahmed Gad
 
Derivation of Convolutional Neural Network (ConvNet) from Fully Connected Net...
Derivation of Convolutional Neural Network (ConvNet) from Fully Connected Net...Derivation of Convolutional Neural Network (ConvNet) from Fully Connected Net...
Derivation of Convolutional Neural Network (ConvNet) from Fully Connected Net...Ahmed Gad
 
Avoid Overfitting with Regularization
Avoid Overfitting with RegularizationAvoid Overfitting with Regularization
Avoid Overfitting with RegularizationAhmed Gad
 
Genetic Algorithm (GA) Optimization - Step-by-Step Example
Genetic Algorithm (GA) Optimization - Step-by-Step ExampleGenetic Algorithm (GA) Optimization - Step-by-Step Example
Genetic Algorithm (GA) Optimization - Step-by-Step ExampleAhmed Gad
 
ICCES 2017 - Crowd Density Estimation Method using Regression Analysis
ICCES 2017 - Crowd Density Estimation Method using Regression AnalysisICCES 2017 - Crowd Density Estimation Method using Regression Analysis
ICCES 2017 - Crowd Density Estimation Method using Regression AnalysisAhmed Gad
 
Backpropagation: Understanding How to Update ANNs Weights Step-by-Step
Backpropagation: Understanding How to Update ANNs Weights Step-by-StepBackpropagation: Understanding How to Update ANNs Weights Step-by-Step
Backpropagation: Understanding How to Update ANNs Weights Step-by-StepAhmed Gad
 
Computer Vision: Correlation, Convolution, and Gradient
Computer Vision: Correlation, Convolution, and GradientComputer Vision: Correlation, Convolution, and Gradient
Computer Vision: Correlation, Convolution, and GradientAhmed Gad
 
Python for Computer Vision - Revision
Python for Computer Vision - RevisionPython for Computer Vision - Revision
Python for Computer Vision - RevisionAhmed Gad
 
Anime Studio Pro 10 Tutorial as Part of Multimedia Course
Anime Studio Pro 10 Tutorial as Part of Multimedia CourseAnime Studio Pro 10 Tutorial as Part of Multimedia Course
Anime Studio Pro 10 Tutorial as Part of Multimedia CourseAhmed Gad
 
Brief Introduction to Deep Learning + Solving XOR using ANNs
Brief Introduction to Deep Learning + Solving XOR using ANNsBrief Introduction to Deep Learning + Solving XOR using ANNs
Brief Introduction to Deep Learning + Solving XOR using ANNsAhmed Gad
 
Operations in Digital Image Processing + Convolution by Example
Operations in Digital Image Processing + Convolution by ExampleOperations in Digital Image Processing + Convolution by Example
Operations in Digital Image Processing + Convolution by ExampleAhmed Gad
 
MATLAB Code + Description : Real-Time Object Motion Detection and Tracking
MATLAB Code + Description : Real-Time Object Motion Detection and TrackingMATLAB Code + Description : Real-Time Object Motion Detection and Tracking
MATLAB Code + Description : Real-Time Object Motion Detection and TrackingAhmed Gad
 
MATLAB Code + Description : Very Simple Automatic English Optical Character R...
MATLAB Code + Description : Very Simple Automatic English Optical Character R...MATLAB Code + Description : Very Simple Automatic English Optical Character R...
MATLAB Code + Description : Very Simple Automatic English Optical Character R...Ahmed Gad
 
Graduation Project - Face Login : A Robust Face Identification System for Sec...
Graduation Project - Face Login : A Robust Face Identification System for Sec...Graduation Project - Face Login : A Robust Face Identification System for Sec...
Graduation Project - Face Login : A Robust Face Identification System for Sec...Ahmed Gad
 

More from Ahmed Gad (20)

ICEIT'20 Cython for Speeding-up Genetic Algorithm
ICEIT'20 Cython for Speeding-up Genetic AlgorithmICEIT'20 Cython for Speeding-up Genetic Algorithm
ICEIT'20 Cython for Speeding-up Genetic Algorithm
 
NumPyCNNAndroid: A Library for Straightforward Implementation of Convolutiona...
NumPyCNNAndroid: A Library for Straightforward Implementation of Convolutiona...NumPyCNNAndroid: A Library for Straightforward Implementation of Convolutiona...
NumPyCNNAndroid: A Library for Straightforward Implementation of Convolutiona...
 
Python for Computer Vision - Revision 2nd Edition
Python for Computer Vision - Revision 2nd EditionPython for Computer Vision - Revision 2nd Edition
Python for Computer Vision - Revision 2nd Edition
 
Multi-Objective Optimization using Non-Dominated Sorting Genetic Algorithm wi...
Multi-Objective Optimization using Non-Dominated Sorting Genetic Algorithm wi...Multi-Objective Optimization using Non-Dominated Sorting Genetic Algorithm wi...
Multi-Objective Optimization using Non-Dominated Sorting Genetic Algorithm wi...
 
M.Sc. Thesis - Automatic People Counting in Crowded Scenes
M.Sc. Thesis - Automatic People Counting in Crowded ScenesM.Sc. Thesis - Automatic People Counting in Crowded Scenes
M.Sc. Thesis - Automatic People Counting in Crowded Scenes
 
Derivation of Convolutional Neural Network from Fully Connected Network Step-...
Derivation of Convolutional Neural Network from Fully Connected Network Step-...Derivation of Convolutional Neural Network from Fully Connected Network Step-...
Derivation of Convolutional Neural Network from Fully Connected Network Step-...
 
Introduction to Optimization with Genetic Algorithm (GA)
Introduction to Optimization with Genetic Algorithm (GA)Introduction to Optimization with Genetic Algorithm (GA)
Introduction to Optimization with Genetic Algorithm (GA)
 
Derivation of Convolutional Neural Network (ConvNet) from Fully Connected Net...
Derivation of Convolutional Neural Network (ConvNet) from Fully Connected Net...Derivation of Convolutional Neural Network (ConvNet) from Fully Connected Net...
Derivation of Convolutional Neural Network (ConvNet) from Fully Connected Net...
 
Avoid Overfitting with Regularization
Avoid Overfitting with RegularizationAvoid Overfitting with Regularization
Avoid Overfitting with Regularization
 
Genetic Algorithm (GA) Optimization - Step-by-Step Example
Genetic Algorithm (GA) Optimization - Step-by-Step ExampleGenetic Algorithm (GA) Optimization - Step-by-Step Example
Genetic Algorithm (GA) Optimization - Step-by-Step Example
 
ICCES 2017 - Crowd Density Estimation Method using Regression Analysis
ICCES 2017 - Crowd Density Estimation Method using Regression AnalysisICCES 2017 - Crowd Density Estimation Method using Regression Analysis
ICCES 2017 - Crowd Density Estimation Method using Regression Analysis
 
Backpropagation: Understanding How to Update ANNs Weights Step-by-Step
Backpropagation: Understanding How to Update ANNs Weights Step-by-StepBackpropagation: Understanding How to Update ANNs Weights Step-by-Step
Backpropagation: Understanding How to Update ANNs Weights Step-by-Step
 
Computer Vision: Correlation, Convolution, and Gradient
Computer Vision: Correlation, Convolution, and GradientComputer Vision: Correlation, Convolution, and Gradient
Computer Vision: Correlation, Convolution, and Gradient
 
Python for Computer Vision - Revision
Python for Computer Vision - RevisionPython for Computer Vision - Revision
Python for Computer Vision - Revision
 
Anime Studio Pro 10 Tutorial as Part of Multimedia Course
Anime Studio Pro 10 Tutorial as Part of Multimedia CourseAnime Studio Pro 10 Tutorial as Part of Multimedia Course
Anime Studio Pro 10 Tutorial as Part of Multimedia Course
 
Brief Introduction to Deep Learning + Solving XOR using ANNs
Brief Introduction to Deep Learning + Solving XOR using ANNsBrief Introduction to Deep Learning + Solving XOR using ANNs
Brief Introduction to Deep Learning + Solving XOR using ANNs
 
Operations in Digital Image Processing + Convolution by Example
Operations in Digital Image Processing + Convolution by ExampleOperations in Digital Image Processing + Convolution by Example
Operations in Digital Image Processing + Convolution by Example
 
MATLAB Code + Description : Real-Time Object Motion Detection and Tracking
MATLAB Code + Description : Real-Time Object Motion Detection and TrackingMATLAB Code + Description : Real-Time Object Motion Detection and Tracking
MATLAB Code + Description : Real-Time Object Motion Detection and Tracking
 
MATLAB Code + Description : Very Simple Automatic English Optical Character R...
MATLAB Code + Description : Very Simple Automatic English Optical Character R...MATLAB Code + Description : Very Simple Automatic English Optical Character R...
MATLAB Code + Description : Very Simple Automatic English Optical Character R...
 
Graduation Project - Face Login : A Robust Face Identification System for Sec...
Graduation Project - Face Login : A Robust Face Identification System for Sec...Graduation Project - Face Login : A Robust Face Identification System for Sec...
Graduation Project - Face Login : A Robust Face Identification System for Sec...
 

Recently uploaded

Tree View Decoration Attribute in the Odoo 17
Tree View Decoration Attribute in the Odoo 17Tree View Decoration Attribute in the Odoo 17
Tree View Decoration Attribute in the Odoo 17Celine George
 
How to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 DatabaseHow to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 DatabaseCeline George
 
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQ-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQuiz Club NITW
 
Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1GloryAnnCastre1
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management SystemChristalin Nelson
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfPrerana Jadhav
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfJemuel Francisco
 
Sulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their usesSulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their usesVijayaLaxmi84
 
CHEST Proprioceptive neuromuscular facilitation.pptx
CHEST Proprioceptive neuromuscular facilitation.pptxCHEST Proprioceptive neuromuscular facilitation.pptx
CHEST Proprioceptive neuromuscular facilitation.pptxAneriPatwari
 
Using Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea DevelopmentUsing Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea Developmentchesterberbo7
 
4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptxmary850239
 
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptxDIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptxMichelleTuguinay1
 
4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptxmary850239
 
Indexing Structures in Database Management system.pdf
Indexing Structures in Database Management system.pdfIndexing Structures in Database Management system.pdf
Indexing Structures in Database Management system.pdfChristalin Nelson
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxkarenfajardo43
 
Mythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWMythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWQuiz Club NITW
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfPatidar M
 

Recently uploaded (20)

Tree View Decoration Attribute in the Odoo 17
Tree View Decoration Attribute in the Odoo 17Tree View Decoration Attribute in the Odoo 17
Tree View Decoration Attribute in the Odoo 17
 
How to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 DatabaseHow to Make a Duplicate of Your Odoo 17 Database
How to Make a Duplicate of Your Odoo 17 Database
 
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITWQ-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
Q-Factor HISPOL Quiz-6th April 2024, Quiz Club NITW
 
Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1Reading and Writing Skills 11 quarter 4 melc 1
Reading and Writing Skills 11 quarter 4 melc 1
 
Transaction Management in Database Management System
Transaction Management in Database Management SystemTransaction Management in Database Management System
Transaction Management in Database Management System
 
Narcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdfNarcotic and Non Narcotic Analgesic..pdf
Narcotic and Non Narcotic Analgesic..pdf
 
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdfGrade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
Grade 9 Quarter 4 Dll Grade 9 Quarter 4 DLL.pdf
 
Sulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their usesSulphonamides, mechanisms and their uses
Sulphonamides, mechanisms and their uses
 
CHEST Proprioceptive neuromuscular facilitation.pptx
CHEST Proprioceptive neuromuscular facilitation.pptxCHEST Proprioceptive neuromuscular facilitation.pptx
CHEST Proprioceptive neuromuscular facilitation.pptx
 
Using Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea DevelopmentUsing Grammatical Signals Suitable to Patterns of Idea Development
Using Grammatical Signals Suitable to Patterns of Idea Development
 
4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx4.11.24 Poverty and Inequality in America.pptx
4.11.24 Poverty and Inequality in America.pptx
 
Faculty Profile prashantha K EEE dept Sri Sairam college of Engineering
Faculty Profile prashantha K EEE dept Sri Sairam college of EngineeringFaculty Profile prashantha K EEE dept Sri Sairam college of Engineering
Faculty Profile prashantha K EEE dept Sri Sairam college of Engineering
 
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptxDIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
DIFFERENT BASKETRY IN THE PHILIPPINES PPT.pptx
 
4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx4.11.24 Mass Incarceration and the New Jim Crow.pptx
4.11.24 Mass Incarceration and the New Jim Crow.pptx
 
Indexing Structures in Database Management system.pdf
Indexing Structures in Database Management system.pdfIndexing Structures in Database Management system.pdf
Indexing Structures in Database Management system.pdf
 
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptxINCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
INCLUSIVE EDUCATION PRACTICES FOR TEACHERS AND TRAINERS.pptx
 
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptxGrade Three -ELLNA-REVIEWER-ENGLISH.pptx
Grade Three -ELLNA-REVIEWER-ENGLISH.pptx
 
prashanth updated resume 2024 for Teaching Profession
prashanth updated resume 2024 for Teaching Professionprashanth updated resume 2024 for Teaching Profession
prashanth updated resume 2024 for Teaching Profession
 
Mythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITWMythology Quiz-4th April 2024, Quiz Club NITW
Mythology Quiz-4th April 2024, Quiz Club NITW
 
Active Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdfActive Learning Strategies (in short ALS).pdf
Active Learning Strategies (in short ALS).pdf
 

Introduction to Prolog (PROramming in LOGic)

  • 1. Prolog as Part of Artificial Intelligence Course By Ahmed Fawzy Gad Faculty of Computers and Information (FCI) Menoufia University Egypt ahmed.fawzy@ci.menofia.edu.eg ‫المنوفية‬ ‫جامعة‬ ‫والمعلومات‬ ‫الحاسبات‬ ‫كلية‬ ‫األقسام‬ ‫جميع‬ ‫اإلصطناعي‬ ‫الذكاء‬ MENOUFIA UNIVERSITY FACULTY OF COMPUTERS AND INFORMATION ALL DEPARTMENTS ARTIFICIAL INTELLIGENCE ‫المنوفية‬ ‫جامعة‬
  • 2. AI Course Pre-requests  Linear Algebra (e.g. vectors, spaces).  Probability Theory.  Set Theory.  Data Structures (e.g. trees, graphs, stacks).  Programming Experience (Java). Extra Knowledge  Machine Learning.  Optimization Techniques.
  • 3. Prolog Course Syllabus Week 1  Review about Computer Languages Categories. o Imperative Languages. o Declarative Languages. o Examples.  Beginner-Professional Java GUI.  Adding 3 Numbers.  Pure Imperative Language – Assembly.  Procedural – Java.  Declarative.  Introduction to Prolog. o Prolog Core Functions.  Problems Solved by Prolog. o Examples.  Students Heights.  Solutions.  Family.  Solutions.  Manual Prolog Tasks Implementation. o Examples.  Students Heights.  Gender Classification.  Prolog Implementations.  SWI-Prolog. o Installing SWI-Prolog.  Accessing SWI-Prolog Command-Line. o Built-in Command-Line Tool. o CMD.  SWI-Prolog File Extensions.  SWI-Prolog Basics. o Prolog Programs.  Creating Prolog Program.  Prolog Clauses.  Prolog Clauses Types. o Facts. o Rules. o Questions.  Prolog Clauses Components. o Head. o Body.  Prolog Clauses – Components Mapping.  Facts.
  • 4. o Examples. o Facts General Structure.  Relations.  Arguments. o Facts and Arguments.  Facts without Arguments.  Creating Relations.  Asking Questions/Making Queries. o Loading Prolog Program.  GUI.  Commands. o Questions Answers.  True.  False.  Error.  Others.  Facts with Single Argument.  Creating Relations.  Asking Questions/Making Queries. o Loading Prolog Program.  Program with Multiple Facts of Same Relation.  Creating Relations.  Asking Questions/Making Queries. o Loading Prolog Program.  Program with Multiple Relations.  Creating Relations.  Asking Questions/Making Queries. o Loading Prolog Program. Week 2  Miscellaneous Topics. o Programs with Same Relation Name and Arguments Number. o Prolog Question Goals.  Question with Single Goal.  Question with Multiple Goals. o Contiguous Relations. o Loading Prolog Program.  Double-Clicking Prolog Program.  Built-in Tool GUI.  Commands.  Consult.  consult Alias.  Load a Program in the CWD. o Returning the SWI-Prolog CWD.
  • 5. o Change SWI-Prolog CWD.  cd.  working_directory.  Prolog Terms. o What are the Prolog Terms? o Constants.  Atoms.  Atom Contents.  Wrong Atoms.  Numbers. o Variables.  Variables Naming.  Wrong variables. o Compound Terms.  Automatic Backtracking. o Traditional Single Relation Question. o Prolog Questions Answers – Others.  Backtracking with single answer satisfying the goal.  Backtracking with multiple answers satisfying the goal.  Automatic Backtracking Definition.  Facts with Multiple Arguments. o Family Tree Problem.  Check Solvability using Prolog. o Creating Relations.  Select Appropriate Clause Type.  Appropriate Relations.  Appropriate Number of Arguments. o Asking Questions.  Traditional Questions – Atoms.  Parent-Child Combinations – Omitting Print – Special Variable.  Advanced Questions – Variables.  Questions Solutions.  Solutions Explanation. o Grandparent. o Siblings. o Cousins.  Prolog Predicates. o Predicate Structure. o Cousins Predicate.  Printing Message.  write.  print.  New Line.  nl.
  • 6. o Grandparent Predicate. o Siblings Predicate.  Prolog Structure with Predicates.  Family Tree Print Drawback. o Modified Predicates.  Siblings.  Static Solution.  Dynamic Solution.  Cousins. o Complete Family Tree Code with Predicates. Week 3  Rules  Prolog Comparison Operators  Math in Prolog  Prolog Arithmetic Operations  Mathematical Predicates  Trigonometry Predicates
  • 7. ****Week 1**** Review about Computer Languages Categories There are different categories of computer languages and each category has its own characteristics. They can be categorized as follows:  Imperative Programming. o Procedural Programming. o Object-Oriented Programming.  Declarative Programming. o Functional Programming. o Logic Programming. Imperative Programming In imperative programing, the programmer gives the computer the detailed steps that it can follow from receiving the input until generating the output. It uses an imperative style where the programmer gives commands and the computer just executes these commands and return the results to the programmer and no more. The programmer gives the computer orders in the form of instructions that have no more simplifications. I don`t know anything about how to find the required result and you should tell me what I can do in details to find the result. Declarative Programming In declarative programming, the programmer just tells the computer the required results without describing how to get these results. The language itself has its logic to determine how to get the results without intervention of the programmer. It knows everything including the sequence of execution. Just declare the required output and I know how to reach that output using my internal logic. Examples to understand the difference between imperative and declarative programming Example 1: Imperative and declarative programming are like dealing with a beginner and a professional. When you want to do a task like creating a Java GUI, you need to give the Java beginner an order to do the task in addition to explaining how to do that task step-by-step like:  Which IDE to use?  How to create a JFrame?  How to add a JButton?  How to create an action? and so on. The beginner have no experience on how to create a Java GUI. But you can give an order to the professional to do the task without further details. The professional have much experience helping to do the task. Example 2: The most pure imperative language is Assembly because the computer knows nothing and take all commands from the programmer.
  • 8. Example to add two 3 using Assembly: mov eax, 15: Move 15 into the EAX register. mov ebx, 20: Move 20 into the EBX register. add eax, ebx: Add the EAX and EBX then store the results in EAX. add eax, 5: Add the 5 to EAX then store the results in EAX. In the previous example, the programmer told the computer how to the task in details from storing the data into registers to adding the results. Most of the recent languages like Java, C, C++, Python, and PHP are imperative but not pure imperative. They can be specifically called procedural. In procedural programming, the computer knows how to do some tasks and can do it without waiting for the programmer orders. The programmer can gives the computer some abstract orders in addition to specifying the sequence in which the commands are to be executed. So procedural programming is imperative but not pure imperative. Imperative – Procedural  int arr_sum = 0;  int [] num_arr = {15, 20, 5};  for(int i=0; i<num_arr.length; i++){ o arr_sum + = num_arr[i];  } Note that the previous code is not pure imperative because the computer knows how to do some operations on its own like storing the data in memory automatically. So it can be said procedural because the programmer decides the sequence of execution. Declarative  sum(15 20 5). This is a very simple task to do in declarative programming languages. MySQL may be regarded a declarative language. One can say that in Java, there is an already existing method to do the sum. So why Java is not a declarative language? This is because behind the scenes, there is an actual implementation for the sum() in Java that go into details of creating an array, looping through it, and summing the results. But in declarative there is no way to go into these details. Also never forget that the correct way of programming is the manual implementation of programs step-by-step and the methods are just existing for making the life easier.
  • 9. Introduction to Prolog Prolog is a logic programing language which is a branch from the declarative programming languages. Prolog stands for PROgramming in LOGic. Prolog was developed in 1972. As being a declarative language, Prolog doesn`t wait for the programmer to tell it how to do tasks but it actually knows how to do tasks by itself. Prolog Core Functions Prolog differs from usual programming languages because Prolog is centered around some basic mechanisms like:  Pattern Matching.  Tree-based Data Structuring.  Automatic Backtracking. Problems Solved by Prolog Prolog is suitable for problems that can be solved logically including objects, specifically structured objects that can be represented in a structured or hierarchical way, and relationships among them. So whenever the problem is formulated with objects it can be solved using Prolog. A problem consisting of three persons A, B, and C with each person has three properties (eating, working, sleeping) is a typical problem solved by Prolog to find the relation among them like A and B eat the same food or work in the same place. Prolog programming consists of defining relations and creating queries about the relations. Generally, Prolog is suitable for AI programming but not numerical programming. Examples Example 1: Height of a group of students:  Salah`s height is 1.7 meters.  Magdy`s height is 1.5 meters.  Ramy`s height is 1.6 meters.  Gamal`s height is 1.55 meters.  Maher`s height is 1.4 meters.  Sami`s height is 1.5 meters. What are the possible student's orders in the class for a good vision? What is the best possible student's order in the class for a good vision?
  • 10. Example 2:  Ahmed is the father of Mohamed.  Mohamed is the brother of Sami.  Sami is the friend of Maher.  Maher is the cousin of Maged. Can Mohamed and Maged be relatives or friends? Manual Prolog Tasks Implementation What can be done using Prolog can be created using the normal programming languages like Java and C++. So using, say Java, you can do the same tasks performed using Prolog. But it will add more complexity.
  • 11. For the classroom example, it can be implemented easily in Java. The required steps to do the task in Java are:  Read the data.  Loop through it.  Compare heights.  Order heights in ascending order. Another example show that some Prolog problems can be implemented easily manually.  Ahmed is male.  Dina is female.  Mohamed is male.  Samir is male.  Maha is female. A command in Prolog can be as follows: male(ahmed). Prolog will print true if ahmed is male and false if ahmed is female. But using Java, you are required to do all of these tasks:  Read the data.  Loop through it.  Check if the name is "ahmed".  After reaching ahmed, return its gender.  If the gender of ahmed is male print true, otherwise print false. You can find that the previous task is trivial to implement in Java without using Prolog. A single database query can fetch the gender of the name ahmed. Yes, you are right that this task is very simple to implement manually in Java without using Prolog but there are other queries that can`t be created using just a simple database queries that we can handle later. Prolog Implementations Prolog was firstly developed in 1972. But there was a problem in Prolog. Prolog was not supporting a large number of applications. To address this problem, some implementations was released for Prolog. Of these implementations:  SWI-Prolog  GNU-Prolog  YAP-Prolog Because each implementation have a different syntax, there was a problem in the language portability [1].
  • 12. [1] Wielemaker, Jan, and Vítor Santos Costa. "On the portability of prolog applications." International Symposium on Practical Aspects of Declarative Languages. Springer Berlin Heidelberg, 2011. SWI-Prolog The Prolog implementation we will use in the course is the SWI-Prolog. Reasons for using the SWI-Prolog are:  Cross-platform.  Free.  Support for GUI via XPCE.  Having an interface to C and Java. SWI-Prolog was developed in 1987 by its original author Jan Wielemaker and implemented based on C and Prolog. The SWI-Prolog site is http://www.swi-prolog.org. Installing SWI-Prolog The first step before using a language is to prepare the required environment for that language. For Java, JDE is to be installed. Also for SWI-Prolog, its environment must be installed. The SWI-Prolog can be downloaded from http://www.swi-prolog.org/download.html. It can be installed easily. After successful installation, the language can be used via its command-line. Accessing SWI-Prolog Command-Line In Windows, there are two ways of accessing the SWI-Prolog command-line: 1. Using the built-in command-line tool swipl-win.exe. 2. Using Windows CMD tool swipl.exe. Calling SWI-Prolog from the built-in command-line swipl-win.exe tool SWI-Prolog can be called from its built-in command-line tool by just opening the swipl-win.exe program. Calling SWI-Prolog from Windows CMD swipl.exe tool It can also get called from CMD using its swipl.exe program. So by changing the directory to the SWI-Prolog installation directory, e.g. C:Program Filesswiplbin, we can enter the swipl command in CMD and the swipl.exe will be called and runs the SWI-Prolog. C:> "C:Program Filesswiplbinswipl" OR C:> cd "C:Program Filesswiplbin" C:> swipl To avoid changing the directory or even typing each time the SWI-Prolog is called, we can save the SWI-Prolog installation directory in the PATH system/user environment variable.
  • 13. The command prompt of the SWI-Prolog is ?-. SWI-Prolog File Extensions For every computer language, there is a very important thing to know about it before typing code which is the file extension in which the code will be written. For example, Java has extensions like .java and .class. C++ extensions are like .cpp, .cc, .h, and .hpp. Also Prolog will have its own extensions. The main file extension for SWI-Prolog is .pl. Due to the confliction with that extension with Perl which have also the .pl extension, another extension is supported for SWI-Prolog which is .pro. To be able to use the alternative extension, .pro, the registry key must be modified. The key can be either of those:  HKEY_CURRENT_USER/Software/SWI/Prolog/fileExtension.  HKEY_LOCAL_MACHINE/Software/SWI/Prolog/fileExtension. So if there is no conflict with other extensions, it is preferred to use the .pl extension. If there is conflict, use the .pro extension. SWI-Prolog Basics A very important note when learning Prolog is to remember that Prolog is different from normal programming languages we previously used. Prolog solves logical problems involving objects and the goal is to create relations between them and asking questions (making queries) about these relations. There are a number of concepts in Prolog that may differ from what we learned before. Prolog Programs. Relations are stored into a Prolog program. The Prolog program is just a simple text file with the Prolog extension .pl. The Prolog program is not similar to the regular programs and can also be called  Database  Knowledgebase. So the first step before creating relations is to create the relations container that holds these relations which is the Prolog program then open it in the SWI-Prolog editor. The file can be created as follows: 1. Open the SWI-Prolog command-line. 2. Click File menu and then New menu item. 3. Enter the Prolog program name with the extension .pl. 4. Finally save the file and it will be opened automatically and ready for receiving relations. Another way to create the Prolog program is just creating a text file but with the .pl extension. Before writing relations inside the Prolog program it will be nice to know that the Prolog program consists of Prolog clauses and the relations are included within these clauses. Each clause is terminated with a full stop. There are three Prolog clauses:
  • 14. 1. Facts: Facts declare things that are always unconditionally true. 2. Rules: Rules declare things that are true depending on a given condition. 3. Questions: The user uses question to ask the program what things are true. Generally, Prolog clauses consists of two parts: 1. Head: 2. Body: Prolog clause body is a list of goals separated by commas. After knowing the types of Prolog clauses and the parts of the clause in general, next is to combine each Prolog clause type with the components that it have. 1. Facts are clauses with a head and an empty body. 2. Rules are clauses with a head and a non-empty body. 3. Questions are clauses with only a body. Relations won`t be defined inside all of these three clauses but within two types only. Relations can be defined using: 1. Facts. 2. Rules. Facts Facts define things that are unconditionally true. Examples of facts:  The sun rises from the east.  For a person named Ahmed Mohamed, saying that parent of Ahmed is Mohamed.  Water boils at 100 degrees Celsius.  Humans die when the heart stops.  Ahmed is male. Prolog facts are clauses with a head and an empty body used for defining Prolog relations. The fact is just a tuple consisting of N arguments of that form: <relation-name>(<argument1>, <argument2>, ..., <argumentN>). Where N can be any non-negative integer (0, 1, 2, …). Fact syntax consists of three parts: 1. Relation Name 2. List of Arguments 3. Full Stop But note that the name of the relations and the arguments must start with a lowercase letter. A tuple in computer programming refers to an ordered set of values. These values are separated using a comma. For each relation, specify the facts as n-tuples of objects that satisfy that relation. Facts can be: 1. Facts without arguments. 2. Facts with arguments.
  • 15. Facts without Arguments The fact in this case is just the relation name. Examples: sunny. So write that fact inside the Prolog program .pl file, save the file, and close it. Note: Now, relations are written into facts. Facts are clauses. Clauses are written into Prolog programs. After creating relations with facts, we did half of the job. The second half is to make questions/queries about such relations. The questions/queries are asked via the SWI-Prolog command-line by asking a question and SWI- Prolog answers these questions. To be able to ask a question/query, the SWI-Prolog must be in the query mode. The query mode is indicated using the ?- command prompt. Before making the query/question about a relation inside a SWI-Prolog program, it is required to load the program. The program is loaded in SWI-Prolog using two ways:  GUI: File>Consult then select the Prolog program.  Command: Using the consult('<file-path>') command or its abbreviation ['<file-path>']. After successfully loading the SWI-Prolog program, next is to ask questions. The questions will be asked by entering the relation name inside the fact. For example: ?- sunny. Because the question is a Prolog clause, it must be terminated by a full stop. Don`t forget that. Questions Answers Answers to Prolog questions can be:  True.  False.  Error.  Others. Usually, the SWI-Prolog responds by either a true or false. For facts without arguments, if the relation under query was found, the Prolog returns true. If the relation was not found, Prolog will gives an error. It will return false for facts with arguments. Facts with Arguments Facts can be more advanced than just a relation name and can also include arguments. We will start by facts with a single argument. For example, we can create a fact with a relation named male with one argument which is the person name. male(<personName>). But make sure that the argument begins with a lowercase letter and capitalize the first letter of words other than the first word if the name consists of multiple words.
  • 16. So the fact with a relation name male and one arguments will be like this: male(ahmed). This fact says that "ahmed is male". After creating that fact, next is to save the Prolog program and load the program inside Prolog to make questions. Yes the program was loaded earlier but to apply the modifications the program must be loaded again. The questions can be like: ?- male(ahmed). The SWI-Prolog will search the program for a relation named 'male'. If it was found it will search for an argument named 'ahmed'. If both the relation and the argument were found, Prolog will return true. If the argument was not found, Prolog will return false. If the relation was not found, Prolog will gives an error. Remember that. For example, try to make questions with arguments that doesn`t exist in the program like: ?- male(mohamed). You will notice that the Prolog answers with false meaning that it can`t find a fact that says "mohamed is male". Program with Multiple Facts of Same Relation Try to add multiple facts of the same relation male like that: male(mohamed). male(ali). male(samir). male(khalid). Then save and load the program to ask questions (make queries) like: ?- male(ahmed). ?- male(ali). ?- male(sameh). Program with Multiple Relations Like creating the previous relation named male, we can easily create another relation named female. female(sara). female(ola). female(mai). female(gehad). female(magda). After entering these relations into the program, next is to save and load the program after modifications. After successful loading, try to make questions: ?- male(ola). ?- female(ahmed). ?- male(marwa). ?- male(mohamed). ?- female(gehad).
  • 17. Comments in Prolog. As regular computer languages, Prolog has comments. Comments in Prolog can be:  Single-line: %.  Multiple-lines: /* … */.
  • 18. ****Week 2**** Miscellaneous Topics Programs with Same Relation Name and Arguments Number Prolog can`t load more than one program if they have the same relation with the same number of arguments. Program will accept to load programs matched in the relation name but with different arguments like male(ahmed).and male(ahmed, Mohamed). program3 male(ahmed). Error program1 male(ahmed). program4 male(ahmed, mohamed). program2 male(mohamed). Prolog Question Goal Prolog questions consists of one or more goal that must be satisfied. Question with Single Goal Prolog questions can have just a single goal to be satisfied. For example, ?- male(ahmed). This question has a single goal to be satisfied which is to find a male named ahmed. When the answer to the question is positive (e.g. true) we say that the goal was satisfiable. If the answer was negative (e.g. false) we say that the goal was unsatisfiable. Question with Multiple Goals Prolog questions can have more than one goal to be satisfied separated by comma ,. ?- goal1, goal2, goal3, …, goalN. All of these goal must be satisfied in order for the answer to be positive. It is similar to the AND operation. For example: ?- male(ahmed), male(mohamed). ?- male(ahmed), female(ola). This question has two goals to be satisfied. If at least one goal was not satisfied the question will return false. The question will return positive answer if and only if all goals are satisfiable. Contiguous Relations Clauses of the same relations must be contiguous in the Prolog program. Prolog will return an error when trying to load the following program. male(ahmed). male(mohamed).
  • 19. female(mona). male(ali). The reason is that the clauses of the male relation are not contiguous and separated by another relation named female. The following program is correct: male(ahmed). male(mohamed). male(ali). female(mona). Loading Prolog Program Prolog program can be loaded in multiple ways. Double-Clicking Prolog Program The easiest and most intuitive way is by double-clicking the Prolog program. It will automatically open the SWI-Prolog built-in tool with the program already loaded. Built-in Tool GUI Using the GUI of the swipl-win tool we can load a Prolog program using the Consult option in the File menu. Commands The previous two ways to load a Prolog program can work with the SWI-Prolog swipl-win built-in tool but can`t work with Windows CMD. Loading a Prolog program via CMD will be done using commands. consult Using the consult Prolog command we can easily load a Prolog program. That command accepts the Prolog program path as an argument as follows: ?- consult('PATH'). For example: ?- consult('C:/Users/Dell/Documents/Prolog/test2'). ?- consult('C:/Users/Dell/Documents/Prolog/test2.pl'). The extension can be omitted from the command because it is implicitly known as .pl. consult Alias [] A shortcut to load a program using a command by adding the Prolog program path between two square brackets [] as follows: ?- ['PATH']. This does the same job as the consult command. For example: ?- ['C:/Users/Dell/Documents/Prolog/test2']. ?- ['C:/Users/Dell/Documents/Prolog/test2.pl']. Loading a Program in the CWD. Is it required to type the program path each time it is loaded? The answer is no.
  • 20. Prolog swipl-win tool is much like CMD. It has a current path like CMD. In CMD, to load a tool located in a different path than the existing path then the complete tool path or directory must be inserted. But if the tool was located in the current working directory (CWD) of CMD then just the tool name can be inserted. swipl-win has a similar behavior. If the Prolog program was located in the CWD in which the tool exists then no need to write the complete path or directory. But if the file was located in a different path than the path at which the tool exist then the path must be inserted. Returning the SWI-Prolog CWD. But how to know the current path of the swipl-win tool? This is via the pwd. command. PWD is short for Current Working Directory. ?- pwd. After knowing the current directory of the swipl-win tool we can decide how to load the Prolog program. If the Prolog program was in the current path then just the Prolog program name is required to load the program. For example: ?- consult(test2). ?- [test2]. Normally if the Prolog program was in different location then there are two ways to load it. The first is to type its path as an argument to consult or [] as explained earlier. Change SWI-Prolog Current Directory The second is to change the current path of the SWI-Prolog. The path can be changed using the cd command with the following signature: ?- cd(NEW_PATH). For example: ?- cd('C:UsersDellDocumentstemp_folder'). Another command that can change the directory is called working_directory with the following signature: ?- working_directory(OLD, NEW). For example: ?- working_directory(CWD, C:UsersDellDocumentstemp_folder'). Prolog Terms Previously we creates two relations named male and female inside a fact with a single argument. After creating the relations next was to ask questions. The questions asked was of that form: Is the person <personName> is male? Is the person <personName> is female? There are other questions to be asked like:  What are the persons that are male?  What are the persons that are female?
  • 21. The previous questions are very simple and doesn`t reflect the intelligence in Prolog. It is just like searching a database. Is it possible to use a language like Prolog to just create search in a database while there are other languages like MySQL that can do that tasks better than Prolog? Prolog is not restricted to do operations like searching in a database but as more arguments and more relations existing in the Prolog program there will be more tasks that are not just searching a database. To be able to create questions of that form, we need to know about Prolog terms. What are the Prolog Terms? All Prolog data structures are called terms. So any way in Prolog used to store data are called terms. Prolog has three main terms: 1. Constants. 2. Variables. 3. Complex or Compound Terms. Constants include two terms: 1. Atoms. 2. Numbers. Constants Constant is something that never changes. Constant in Prolog can be either atoms or numbers. Atoms Atoms are term type we used in previous examples. Atoms are like strings in Java and C++. An atom is a string of characters made up of:  Uppercase letters (A-Z).  Lowercase letters (a-z).  Digits (0-9).  Underscore (_). Important note: Atoms must start with a lowercase letter. Terms Constants Atoms Numbers Variables Compound Terms
  • 22. Examples:  ahmedMohamed  ahmed_mohamed  way2home Regular atom can`t:  Contain spaces.  Contain special characters like !, @, %, $, #, and so on.  Start with an uppercase letter. So the following are invalid atoms:  Ahmed  #OfUsers  ahmed mohamed But an atom can do all of those if it was enclosed between single quotes. So to make the previous atoms valid, enclose them between single quotes ' ':  'Ahmed'  '#Users'  'ahmed mohamed' Generally speaking, anything data enclosed between single quotes is an atom. Numbers Numbers in any computer language can be either:  Integer (…, -3, -2, -1, 0, 1, 2, 3, …).  Floating-point like π, 728.1312, -131.63. It is not common to use floating-point numbers in Prolog but they are available. This is a proof that Prolog is not intended for numerical programming. Variables A variable is a string of characters made up of:  Uppercase letters (A-Z).  Lowercase letters (a-z).  Digits (0-9).  Underscore (_). Important note: Variables must start with an uppercase letter or underscore and can`t be enclosed between single or double quotes. Remember: Whenever you see a string starting with an uppercase letter, it will be a variable. If it starts by a lowercase letter, it is an atom. If it was enclosed between single quotes it is also an atom. Anonymous Variable
  • 23. Variable can be just an underscore (_) but it is a special variable in Prolog called anonymous variable. Examples:  X  _X  X1  X_Y Variables can`t:  Contain spaces.  Contain special characters like !, @, %, $, #, and so on.  Start with a lowercase letter. So the following are invalid variables:  x  #OfUsers  X Y Automatic Backtracking After having knowledge about what are the terms (specially variables) in Prolog, we can start making new questions to Prolog rather than the simple ones discussed previously. Previously we asked questions like: Is ahmed is male? Is mona is female? These questions are written as follows in Prolog: male(ahmed). female(mona). Now we will ask questions in that form: What are the names of males? What are the names of females? These questions are written as follows in Prolog: male(X). female(X). Prolog Questions Answers – Others The difference between these two types of questions is using variables rather than atoms. We have previously said that Prolog answers can be true, false, error, or others and knew when the answer can be true, false, and error. For example, when asking that question male(ahmed).. The answer can be either true, false, or error. True if there is a male called ahmed, false if no male called ahmed was found in the knowledgebase, and error if the relation name or the number of arguments were not matched any fact in the program.
  • 24. Other answers than these three answers can be returned for question like male(X).. It can return true, false, or error as discussed previously and can also return other answers which is the name of males in the knowledgebase. Backtracking with single answer satisfying the goal When asking that question male(X)., Prolog searches the knowledgebase for all males and the first male found will be returned into the variable X. Because there is only one male in the database, Prolog just returns that male into the variable X and terminates the execution of the question. The effect of automatic backtracking will appear when there are multiple relations satisfying the goal of the question. Backtracking with multiple answers satisfying the goal When there are multiple relations satisfying the goal of the question the effect of automatic backtracking appears. Because there may be multiple males in the dataset, Prolog provides a way to get the alternative males which is called automatic backtracking. Automatic backtracking in Prolog is to know the alternative solutions that satisfy a given relation. Alternative solutions can be found using semicolon ;. For each semicolon ; entered, a new solution will be returned into the variable X until reaching the end of the list of solutions. Example: male(X). X = ahmed ; X = mohamed ; X = ali ; X = samir ; X = khalid. Facts with Multiple Arguments Suppose that it is required to define the following family tree using a Prolog program.
  • 25. Check Solvability using Prolog Because the problem can be formulated as a hierarchy like a tree it can be solved in Prolog. Major steps to deal with a problem in Prolog are: 1. Creating Relations. 2. Asking Questions. Creating Relations Before creating relations, it is required to decide the type of Prolog clauses that is convenient with the problem to hold the relations. Select Appropriate Clause Type From the problem nature, it is clear that the problem presents things that are always true. So the type of Prolog clauses to use is fact. After determining what type of Prolog clauses to be used, it is required to determine the parts of the facts. Remember that facts consist of a relation and a number of arguments. So we must define the following:  Relation name.  Number of arguments. Appropriate Relations Because the tree presents a child-parent relationship, good relations to be used are:  Child.  Parent. Appropriate Number of Arguments Suppose we selected the parent relationship to model that problem, next is to determine the number of arguments it should take. The parent relation maps a parent to its child, so there should be two arguments to represent the following: 1. Parent name. 2. Child name. After determining the clause type, relation name, and number of arguments, we can write the general form of the fact as follows: parent(<parentName>, <childName>). At first, it is fine to list all the parent-child facts as statements in English and map each statement to a fact. Fact Statement SWI-Prolog Representation Mohamed is parent of Ahmed. parent(mohamed,ahmed). Ahmed is parent of Kamal. parent(ahmed, kamal). Ahmed is parent of Sabry. parent(ahmed, sabry).
  • 26. Ahmed is parent of Mona. parent(ahmed, mona). Kamal is parent of Maher. parent(kamal, maher). Sabry is parent of Hala. parent(sabry, hala). Sabry is parent of Ghada. parent(sabry, ghada). The complete SWI-Prolog facts for the parent relation are as follows: parent(mohamed, ahmed). parent(ahmed, kamal). parent(ahmed, sabry). parent(ahmed, mona). parent(kamal, maher). parent(sabry, hala). parent(sabry, ghada). Note: The relation name in addition to the arguments start by lowercase letters. Asking Questions After saving the Prolog program and loading it we come to the step of asking questions and making queries. We want to ask two types of questions: 1. Traditional Questions – Atoms. 2. Advanced Questions – Variables. Traditional Questions – Atoms We will start by the traditional questions in which the arguments are constants (atoms) then move to more advanced questions using variables. Examples of questions and queries: parent(ahmed, mona). parent(kamal, mahar). parent(sabry, magdy). parent(ghada, sabry). As regular, when a question is asked, Prolog searches for the question relation entered which in this case parent with the same number of arguments entered which in this example 2. If any of these conditions not matched, an error will be given. If there was a relation called parent accepting two arguments then matching take place. If the question arguments matched arguments of a fact in the program then Prolog returns true. If the question arguments not matched any of the facts arguments in the program, then Prolog will return false. The previous questions were of this form: Is the parent <parentName> has a child <childName>? For example, the question parent(ahmed, mona). asks Prolog if there is a parent named ahmed has a child named mona. Advanced Questions – Variables
  • 27. As we did earlier, using variables it is possible to make other forms of questions that Prolog can answer like: 1. What are the children of the parent <parentName>? 2. What is the parent of the child <childName>? 3. What are the parent-children combinations? 4. What is the grandparent of the child <childName>? 5. What are the siblings of the child <childName>? (Siblings = Brothers + Sisters). 6. What are the cousins of the child <childName>? The previous examples shows some bit complex operations that can`t be implemented easily in programming languages like Java even if just a single relation with just two arguments are used. This proves that Prolog is the best option for such applications. Note: Set the argument to a variable wherever the argument constant value is missing. The way to do the previous questions is as follows: # Question Statement 1 What are the children of ahmed? 2 What is the parent of ahmed? 3 What are the parent-child combinations? 4 What is the grandparent of kamal? 5 What are the siblings of mona? 6 What are the cousins of maher? The way to do the previous questions is as follows: # Question Statement SWI-Prolog Representation 1 What are the children of ahmed? parent(ahmed, X). 2 What is the parent of ahmed? parent(X, ahmed). 3 What are the parent-child combinations? parent(X, Y). 4 What is the grandparent of kamal? parent(X, kamal), parent(Y, X). 5 What are the siblings of mona? parent(X, mona), parent(X, Y). 6 What are the cousins of maher? parent(A, maher), parent(B, A) , parent(B, C) , parent(C, Cousins). Solutions Explanation The first three questions are easily understood. Wherever the value of the argument is unknown, use a variable instead. The first question gives the parent name value but not the child name. So set the child argument to a variable. The second question gives the child name value but not the parent name. So set the parent argument to a variable. The third question doesn`t give neither the parent name value nor the child name. So set both the parent and child arguments to variables. Parent-Child Combinations – Omitting Print – Special Variable When issuing this command in Prolog: parent(X, Y).
  • 28. Prolog prints both the parent name and child name. If we are interested only in parent names then we can omit the print of the child name by using the special variable _. parent(X, _). To print only the child name not the parent name: parent(_, X). Deeper explanation will be for the last three questions. Note: When the question can`t be answered by just using a single relation think of using multiple relations to find the solution. Grandparent There is no relation named grandparent and thus Prolog can`t answer the question what is the grandparent of? Prolog only knows about the parent relation and thus it can answer question what is the parent of?. So how to use the parent relation to get the grandparent? Because a grandparent is the parent of a parent, the grandparent relationship can be divided into two parent relations. So to find the parent of kamal, just find the parent of kamal then the parent of the parent of kamal. How to make two consecutive questions in Prolog. Ask the first question but replace the full stop in it by a comma then ask the second question terminated normally by a full stop. To find the answer of the question 'What is the grandparent of kamal?' we can create two parent relations as follows: 1. The first question will get the parent of kamal in the variable X. 2. Because the parent of kamal was returned into the variable X, so to know the parent of the parent of kamal we need a second question that asks for the parent of the variable X. grandparent of kamal = parent of parent of kamal. parent of kamal = X. parent of parent of kamal = parent of X. parent of X = Y. This is how to do it in Prolog: parent(X, kamal), parent(Y, X). Siblings Because there is no relation to find the siblings relation and we just can find the parent relation, we have to divide the siblings relation into a number of parent relations. As siblings are the other children of a parent, so to find the siblings of someone, we have to find the parent of that one and then find the children of the parent.
  • 29. The answer of the question 'What are the aiblings of mona?' will be answered using two parent relations:  First one finds the parent of mona and return it into a variable X.  Second relation will find the children of the parent of mona and return it into a variable Y. Siblings of mona = other children of mona `s parent. mona `s parent = X. other children of mona `s parent = other children of X. children of X = Y. This is how to do it in Prolog: parent(X, mona), parent(X, Y). Cousins Because there is no relation to find the cousins, we have to divide it into a number of parent relations. Cousins are the children of someone`s siblings. So to find the cousins of someone, we need to find the grandparent of that one, then find the children of that grandparent and finally find the children of each child. The answer of the question 'What are the aiblings of maher?' will be answered using three parent relations:  Finds the parent of maher and return it into a variable c.  Find the parent of maher`s parent and return it into a variable B.  Find the children of the parent of maher`s parent and return it into a variable C.  Find the children of the children of the parent of maher`s parent and return it into a variable Cousins. cousins of maher = the children of the children of the parent of maher`s parent. maher`s parent = A. cousins of maher are the children of the children of the parent of A. parent of A = B. cousins of maher are the children of the children of B. children of B = C. cousins of maher are the children of C. children of C = Cousins. cousins of maher = Cousins. This is how to do it in Prolog: parent(A, maher), parent(B, A) , parent(B, C) , parent(C, Cousins). Prolog Predicates
  • 30. Each time a cousin relationship is to be found in Prolog we have to enter a long command in the command-line like that: parent(A, <personName>), parent(B, A) , parent(B, C) , parent(C, Cousins). This is tiresome specially for a long number of goals to be entered in the command-line. We can make use of a new concept in Prolog called predicates to overcome this problem. Predicates in Prolog are similar to functions and methods in regular programming languages. So we can write a predicate in Prolog that holds all of work and just access it by a simple command. For example, rather than writing this long question to find the cousin relationship, we can create a predicate called cousins and put all work inside it. Predicate Structure Predicate consists of a number of clauses separated by commas. The last clause of the predicate is terminated by a full stop. Like having input arguments for the functions and methods, Prolog predicate can have a number of arguments and variables as its input. The general structure of a Prolog predicate is as follows: predicate_name(listOfArgumentsAndVariables):- clause1, clause2, clause3, . . . clauseN. cousins Predicate For example, we can create a predicate as a shortcut for finding the cousin relation as follows: cousins(PersonName):- parent(A, PersonName), parent(B, A), parent(B, C), parent(C, Cousins), write('Cousins of '), write(PersonName), write(' are '), write(Cousins). The cousins predicate accepts the person name in the variable PersonName and prints to find its cousins. Note that the cousins predicate uses the parent relation but the parent relation can be defined before or after the cousins predicate. Printing Message parent(A, <personName>), parent(B, A) , parent(B, C) , parent(C, Cousins). cousins(<personName>).
  • 31. The write(D). clause is used to print the value of the variable D. write is one of the built-in predicates in Prolog. Generally, the write() is used to print something on the command-line and the writeln() is used to print something on the command-line and finally make a new line. For example: write('Just a message.'). Similar predicate is print().: print('Just a message.'). New Line A new line can be created using the nl. command. grandparent Predicate We can create another predicate to find the grandparent of a person as follows: grandparent(ChildName):- parent(Parent, ChildName), parent(GrandParent, Parent), write('The parent of '), write(ChildName), write(' is '), write(Parent), writeln('.'), write('The parent of '), write(Parent), write(' is '), write(GrandParent), writeln('.'), write('So the grandparent of '), write(ChildName), write(' is '), write(GrandParent), writeln('.'). The grandparent predicate accepts the child name into the variable ChildName and prints its parent and grandparent names. siblings Predicate Finally we can create a siblings predicate to find the siblings of someone`s name passed in the ChildName variable as follows: siblings(ChildName):- parent(Parent, ChildName), parent(Parent, Siblings), write(Siblings of '), write(ChildName), write(' are '), write(Siblings). Prolog Structure with Predicates
  • 32. After using predicates, we can say that Prolog consists of programs. Programs contains of predicates. Predicates contains clauses. Clauses can be facts, rules, and questions. Clauses contains relations which is the goal of Prolog. Questions are created to query such relations.  Prolog.  Program.  Predicates.  Clauses.  Relations. Drawback When trying to find the siblings of sabry, for example, the result will be: 1. Kamal. 2. Mona. 3. Sabry. sabry is printed in the result and that means Sabry is a sibling of Sabry which is not true. So it is more accurate to say that Siblings of sabry are just: 1. Kamal. 2. Mona. So the question is how to remove sabry from the result. When analyzing the Siblings predicate, it can be easily found that the list of siblings are returned into the Siblings variable. That variable will have three values (Kamal, Mona, and Sabry). We want to remove the sabry value from the list of values of the Siblings variable. That can be done in different ways like:  dif(Siblings, sabry).  Siblings = sabry. Siblings Static Solution The modified siblings predicate is as follows: siblings(ChildName):- parent(Parent, ChildName), parent(Parent, Siblings), dif(Siblings, sabry), write(Siblings of '), write(ChildName), write(' are '), write(Siblings). Dynamic Solution To make that dynamic over any siblings we can remove the static value sabry and use the ChildName variable. The modified siblings predicate is as follows: siblings(ChildName):- parent(Parent, ChildName), parent(Parent, Siblings),
  • 33. dif(Siblings, ChildName), write(Siblings of '), write(ChildName), write(' are '), write(Siblings). Cousins The previous procedure can be applied to the cousins predicate to avoid printing the query person name in the result. The cousins predicate will be modified as follows: cousins(PersonName):- parent(A, PersonName), parent(B, A), parent(B, C), parent(C, Cousins), dif(Cousins, PersonName), write('Cousins of '), write(PersonName), write(' are '), write(Cousins). Complete Family Tree Code with Predicates The complete program is as follows: parent(mohamed, ahmed). parent(ahmed, kamal). parent(ahmed, sabry). parent(ahmed, mona). parent(kamal, maher). parent(sabry, hala). parent(sabry, ghada). cousins(PersonName):- parent(A, PersonName), parent(B, A), parent(B, C), parent(C, Cousins), dif(Cousins, PersonName), write('Cousins of '), write(PersonName), write(' are '), write(Cousins). grandparent(ChildName):- parent(Parent, ChildName), parent(GrandParent, Parent), write('The parent of '), write(ChildName), write(' is '), write(Parent), writeln('.'),
  • 34. write('The parent of '), write(Parent), write(' is '), write(GrandParent), writeln('.'), write('So the grandparent of '), write(ChildName), write(' is '), write(GrandParent), writeln('.'). siblings(ChildName):- parent(Parent, ChildName), parent(Parent, Siblings), dif(Siblings, ChildName), write('Siblings of '), write(ChildName), write(' are '), write(Siblings).
  • 35. ****Week 3**** Rules Creating Rule The statement "student succeeds if the score is more than or equal 50" can`t be inserted into Prolog as a fact but more appropriately using a rule. It can be modelled as follows: ?- suceeds(X) :- X >= 50. This is similar to an IF statement in regular programming languages like Java. Prolog Comparison Operators Greater Than > Less Than < Greater Than Or Equal >= Less Than Or Equal =< Equals =:= Not Equals == Math in Prolog We have previously said that Prolog doesn`t target numerical applications but works with problems including objects. This doesn`t prevent the existence of some simple numerical operations built inside Prolog. Prolog Arithmetic Operations Being familiar to Java or C++, you can imagine that Prolog arithmetic operations like addition can be like that: ?- X = 1 + 2. Where X is the variable that holds the result of adding 1 and 2. But this is not correct. There are two assignment operators in Prolog: 1. is 2. = Explanation of the difference is better explained by an example: ?- X is 1 + 2. ?- X = 1 + 2. The right solution is what uses the is operator. The is operator should only be used when performing arithmetic operations on the RHS of the equation. Mathematical Predicates pow(2, 4, X). %2 to the power 4 = 16 and save it into variable X. X is max(4, 7). X is min(4, 7). X is abs(-4).
  • 36. X is ceiling(3.2). X is floor(3,2). X is round(3,2). integer(3.4). %Returns true if the input is integer and false otherwise. X is log(4). %Logarithm with the e as the base. X is log10(49). %Logarithm with 10 as the base. X is sign(4). %1 if positive, -1 if negative, and 0 if zero. X is sqrt(4). Trigonometry Predicates X is sin(50). X is cos(50). X is tan(50). X is asin(50). X is acos(50). X is atan(50).
  • 37. Miscellaneous Prolog Predicates ls. List files in current folder. edit('SWI-Prolog/program/absolute/path/with/or/without/extension'). Edit the SWI-Prolog program specified by the path. edit. If the SWI-Prolog program was opened by double-clicking it, it can be edited by just edit. without specifying the path. read(prompt): Request input from the user. nl: Prints new line. write(message): Prints a message on the screen. halt(0): Exit Prolog. Editing SWI-Prolog programs:  Open the SWI-Prolog then click File>Edit to select the SWI-Prolog progam.  Use the edit('path'). Command by specifying the SWI-Prolog program name.  Double-click the SWI-Prolog program and enter edit. without adding the path. Notes on naming relations:  The relations have a name that is a noun or a noun phrase. Multiple words in the relation name are separated by underscore _ and each word starts with a lowercase letter.  Try to give the relations an unambiguous names and be aware of symmetry in which the relation name can be read in multiple ways.  For example, the fact parent(A, B) can be read in two ways: 1. A is parent of B. 2. B is parent of A. But of the relation was named parent_child there will be no ambiguity because parent_chils(A, B) means that A is the parent and B is the child. Also try to give arguments a descriptive name with mixed-case letters. E.g. childName instead of child_name starting with a lowercase letter like the relation. Trace the program execution by entering trace. before issuing a command.