This document provides an overview of logic programming concepts using Prolog. It defines key Prolog terms like predicates, facts, rules, clauses, queries, variables, and constants. Examples are given to illustrate Prolog syntax and how to write programs, define relations between objects, and query a Prolog knowledge base to deduce answers. The document also discusses how Prolog databases consist of sets of predicates defined by clauses that are either rules or facts, and how Prolog executes queries by searching these clauses to determine logical answers.
1. Course code: CS213
Course title :
(Programming Languages Concepts)
PART: 4
Prof. Taymoor Mohamed Nazmy
Dept. of computer science, faculty of computer science, Ain Shams uni.
Ex-vice dean of post graduate studies and research Cairo, Egypt
1
4. Introduction
• Prolog is a declarative language, declarative programming is
sometimes called rule-based programming, prolog is one of
symbolic programming languages.
• Rather than describing how to compute a solution, a program
consists of a data base of facts and logical relationships
(rules).
• Rather then running a program to obtain a solution, the user
asks a question.
• When asked a question, the run time system searches through
the data base of facts and rules to determine (by logical
deduction) the answer.
4
5. Applications of Symbolic
Computation
• Relational databases
• Mathematical logic
• Understanding natural language
• Symbolic equation solving
• Many areas of artificial intelligent
5
7. SWI-Prolog
• SWI-Prolog is a good, standard Prolog for
Windows and Linux
• It's licensed under GPL (General Public License),
therefore free
• Downloadable from: http://www.swi-prolog.org/
9. 9
• ‘Predicate’is the name given to the word occurring
before the bracket in a fact or rule:
parent (jane,alan).
• By defining a predicate you are specifying which
information needs to be known for the property
denoted by the predicate to be true.
Predicate Definitions
Predicate name
10.
11. Facts
• John likes Mary
– like(john,mary).
• Names of relationship and objects must begin with a
lower-case letter.
• Relationship is written first (typically the predicate of the
sentence).
• Objects are written separated by commas and are enclosed
by a pair of round brackets.
• The full stop character ‘.’ must come at the end of a fact.
11
12. A fact
• A fact is a clause without a right-hand side.
• father(john).
takes(jane, cs245).
takes(ajit, art302).
12
14. Structure of LogicPrograms
• Programs consist of a set of predicates.
• A predicate is defined by a collection of clauses.
• A clause is either a rule or a fact. If any clause is true,
then the whole predicate is true.
• Clauses are statements about what is true about a
problem, instead of instructions how to accomplish
the solution.
• Programs are executed by posing queries.
14
18. 18
Examples of fact and rule
• A fact asserts some property of an object, or relation
between two or more objects.
e.g. parent(jane,alan).
Can be read as “Jane is the parent of Alan.”
• Rules allow us to infer that a property or relationship
holds based on preconditions.
e.g. parent(X,Y) :- mother(X,Y)
.
= “Person X is the parent of person Y if X is Y’s mother.”
22. • The Prolog system uses the clauses to work out how to
accomplish the solution by searching through the space of
possible solutions.
• Computer Programming in Prolog consists of:
– Declaring some facts about objects and their relationships.
– Declaring some rules about objects and their relationships.
– Asking questions (goals) , queries or about
objects and their relationships.
Structure of LogicPrograms
22
25. A Prolog Program
• The program, sometimes called Database is a
text file (*.pl) that contain the facts and rules.
It contains all the relations needed to define
the problem.
• When you launch a program you are in query
mode represented by the ? – prompt.
• In query mode you ask questions about the
relations described in the program.
• 25
26. • When Prolog is launched the ?- should appear
meaning you are in query mode. In SWI-
Prolog you can load a program by typing the
command [file].
• When the file containing your program is
file.pl. When you have done this you can use
all the facts and rules that are contained in the
program.
26
27. 27
Clauses
• Predicate definitions consist of clauses.
= An individual definition (whether it be a fact or rule).
e.g. mother(jane,alan). = Fact
parent(P1,P2):- mother(P1,P2). = Rule
• A clause consists of a head
• and sometimes a body.
– Facts don’t have a body because they are always true.
head body
28. Clauses
• A clause has a head and a body (Rule) or just a head (Fact).
• A head consists of a predicate name and arguments.
• A clause body consists of a conjunction of terms.
• A clause may be also, the query question.
28
29. 29
Clauses
Clauses have three forms:
hypotheses (facts)
conditions (rules)
goals
assertions (database)
questions
29
• Notation of clauses in Prolog
Head :- Body.
It is equivalent to implication operator “→” in predicate logic.
But the direction is opposite (Body→Head).
Write the period end of the each clauses
32. Facts interpretation
• play(john, susie). /* John play with Susie */
• play(X, John). /* Everyone play with John */
• likes(john, Y). /* John likes everybody */
• likes(john, Y), likes(Y, john). /* John likes everybody
and everybody likes John */
• play(john, mark); play (john,mary). /* John play with
mark or John play with Mary */
• not(likes(john,pizza)). /* John does not like pizza */32
33. Rules
• A rule has a condition and a conclusion
• The conclusion of a Prolog rule is its head
• The condition of a Prolog rule is its body
• If the condition of a rule is true, then it follows
that its conclusion is true also
33
34. 34
A rule Syntax
A prolog rule is called a clause.
A clause has a head, a neck and a body:
father(X,Y) :- parent(X,Y) , male(X) .
head neck body
the head is a rule's conclusion.
The body is a rule's premise or condition.
note:
Read :- as IF
Read , as AND
A . marks the end of input 34
35. Rules examples
• E.G.
– likes(john,X) :- likes(X,cricket).
– “John likes X if X likes cricket”.
– i.e., “John likes anyone who likes cricket”.
• Rules always end with ‘.’.
35
36. Another Example
sister_of (X,Y):- female (X),
parents (X, M, F),
parents (Y, M, F).
X is a sister of Y if
X is a female and
X and Y have same parents
36
37. Rules interpretation
• friends(X,Y) :- likes(X,Y),likes(Y,X).
• /* X and Y are friends if they like each other */
• hates(X,Y) :- not(likes(X,Y)).
• /* X hates Y if X does not like Y. */
• enemies(X,Y) :-not(likes(X,Y)),not(likes(Y,X)).
• /* X and Y are enemies if they don't like each other */
37
38. Prolog Structure – Queries
• A query searches the database for the first fact
that satisfies its goal.
• Questions or queries based on facts
• If a fact is found then it either unifies the variable
with a constant or Prolog returns yes.
• If a fact is not found that meets that condition
then Prolog returns no.
38
39. Example using SWI-Prolog
location(desk, office).
location(apple, kitchen).
location(flashlight, desk).
location('washing machine', cellar).
location(nani, 'washing machine').
location(broccoli, kitchen).
location(crackers, kitchen).
location(computer, office).
?- location(apple, kitchen).
yes
Program
Query
39
40. Arguments
• Arguments contained within brackets and separated by
commas.
mother(jane,alan).
• Arguments also consist of terms, which can be:
– Constants e.g. jane,
– Variables e.g. Person1, or
– Compound terms
Arguments
40
41. Complete Syntax of Terms
Term
Constant VariableCompound Term
Atom Number
alpha17
gross_pay
john_smith
dyspepsia
+
=/=
’12Q&A’
0
1
57
1.618
2.04e-27
-13.6
likes(john, mary)
book(dickens, Z, cricket)
f(x)
[1, 3, g(a), 7, 9]
-(+(15, 17), t)
15 + 17 - t
X
Gross_pay
Diagnosis
_
Names an individual Stands for an individual
unable to be named when
program is written,
use Capital letter
Names an individual
that has parts
41
42. Variables
• Always begin with a capital letter
– ?- likes (john,X).
– ?- likes (john, Something).
• But not
– ?- likes (john,something)
42
43. Example of usage of variable
Facts:
likes(john,flowers).
likes(john,mary).
likes(paul,mary).
Question:
?- likes(john,X)
Answer:
X=flowers and wait
;
mary
;
no
43
44. Conjunctions
• Use ‘,’ and pronounce it as and.
• Example
– Facts:
• likes(mary,food).
• likes(mary,tea).
• likes(john,tea).
• likes(john,mary)
• ?-
• likes(mary,X),likes(john,X).
• Meaning is anything liked by Mary also liked by John?
44
68. 68
Prolog in English
Example Database:
John is the father of Jim.
Jane is the mother of Jim.
Jack is the father of John.
Person 1 is a parent of Person 2 if
Person 1 is the father of Person 2 or
Person 1 is the mother of Person 2.
Person 1 is a grandparent of Person 2 if
some Person 3 is a parent of Person 2 and
Person 1 is a parent of Person 3.
Example questions:
Who is Jim's father?
Is Jane the mother of Fred?
Is Jane the mother of Jim?
Does Jack have a grandchild?
69. 69
Prolog in Prolog
Example Database:
father( john, jim ).
mother( jane, jim ).
father( jack, john ).
parent( Person1, Person2 ) :-
father( Person1, Person2 ;
parent( Person1, Person2 ) :-
mother( Person1, Person2 ).
grandparent( Person1, Person2 ) :-
parent( Person3, Person2 ),
parent( Person1, Person3 ).
Example questions:
?- father( Who, jim ).
?- mother( jane, fred ).
?- mother( jane, jim ).
?- grandparent( jack, _ ).
Example Database:
John is the father of Jim.
Jane is the mother of Jim.
Jack is the father of John.
Person 1 is a parent of Person 2 if
Person 1 is the father of Person 2 or
Person 1 is the mother of Person 2.
Person 1 is a grandparent of Person 2 if
some Person 3 is a parent of Person 2 and
Person 1 is a parent of Person 3.
Example questions:
Who is Jim's father?
Is Jane the mother of Fred?
Is Jane the mother of Jim?
Does Jack have a grandchild?
71. 71
What is Data Abstraction?
• Concept of “Abstraction”
– Allows us to consider the high-level characteristics
of something without getting bogged down in the
details
72. Abstract Data Type (ADT)
• Simplest ADT is a Bag
– items can be added, removed, accessed
– no implied order to the items
– duplicates allowed
• Set
– same as a bag, except duplicate elements not
allowed
72
73. 73
What is an Abstract Data Type?
• Abstract Data Type (ADT)
– Defines a particular data structure in terms of data and operations
• An ADT consists of:
– Declaration of data
– Declaration of operations
– Encapsulation of data and operations : data is hidden from user
and can be manipulated only by means of operations
74.
75. 75
ADT Implementation
• Implementaion of an Abstract Data Type (ADT)
– Hidden from the user
– Same ADT may be implemented in different ways in
different languages
– Some languages offer built-in ADTs and/or features to
be used to implement ADTs (user-define types)
76. ADT and Data Structure
• Abstract data type can be defined as a data structure with
well defined interface, such as stack queue tree.
• Data Structures are containers:
– they hold other data
– arrays are a data structure
– ... so are linked lists
• Other types of data structures:
– stack, queue, tree,
binary search tree, hash table,
dictionary or map, set, and on and on
• Different types of data structures are optimized for certain
types of operations
76
77. Data Structures
• A Data Structure is:
– "An organization of information, usually in computer
memory", for better algorithm efficiency."
82. Core Operations
• Data Structures have three core operations
– a way to add things
– a way to remove things
– a way to access things (without modifying the data)
• Details depend on the data structure
– For instance, a List may need to:
– add at the end
– access by location (index)
– remove by location (index)
• More operations added depending on what data
structure is designed to do
82
83. Implementation-Dependent Data Structures
• Arrays
– Collection of objects stored contiguously in memory
– Accessed through an index
– Linked Lists
• Linear collection of nodes
• Single-linked List – nodes contain references to next node in list
• Double-Linked List – nodes contain reference to next and previous nodes in list
– Trees
• Hierarchical structure
• Nodes reference two or more “children”
83
84. Stacks
• Only access last item inserted
– Expected behavior: Last in, First out (LIFO)
• push (put object on top)
• pop (remove object from top)
• peek / top (look at object on top)
– Other useful operations
• make empty
• Size is empty?
84
85. Queues
• Only access item that has been there the longest
– Expected behavior: First in, First out (FIFO)
• enqueue (insert at the back)
• dequeue (remove from the front)
• front (look at the object at the front)
– Other useful operations
• make empty
• Size is empty?
85
86. Lists
• Linear collection of items
– Sorted List
• Items in list are arranged in a pre-determined ordering
– For instance, alphabetically or by ascending numerical value
– Indexed List
• Items are accessed by position in list
• Additions / deletions can also be done by position
– Unsorted List
• Items are stored without an implicit ordering
86
87. Types of Trees
• A binary tree is restricted to only having 0, 1, or 2 children.
• Binary Search Trees (BSTs)
– Items stored in sorted order
• Heaps
– Items stored according to the “Heap Property” the value stored at a node is greater or
equal to the values stored at the children
• AVL and Red-Black Trees
– BSTs that stay balanced
• Splay Trees
– BST with most recently items at top
• B-Trees
– Another variation of BST
– Nodes can have more than two children
87
90. Concept of Multi
• There are a number of terminologies related to the
concept of multi such as:
• Concurrent,
• Parallelism,
• Multitasking,
• multithreaded,
• Multi processor
• What are the meaning and differences?
90
91. Ordinary Program
• An "ordinary" program consists of data declarations
and assignment and control-flow statements in a
programming language.
• Modern languages include structures such as
procedures and modules for organizing large software
systems through abstraction and encapsulation, but the
statements that are actually executed are still the
elementary statements that compute expressions, move
data and change the flow of control.
• These machine instructions are executed sequentially
on a computer and access data stored in the main or
secondary memories. 91
92. Concurrent Program
• A concurrent program is a set of sequential
programs that can be executed in parallel.
–Process: the word for the sequential
programs that comprise a concurrent
program
–Program: the word for this set of processes.
• Parallel: systems in which the executions of
several programs overlap in time by running
them on separate processors.
92
93. • Concurrent: potential parallelism, in which the
executions may, but need not, overlap; instead,
the parallelism may only be apparent since it
may be implemented by sharing the resources
of a small number of processors, often only
one.
• Like any abstraction, concurrent programming
is important because the behavior of a wide
range of real systems can be modeled and
studied without unnecessary detail.
• What is the difference between concurrent and
parallel programming?
93
95. The Challenge of Concurrent
Programming
• The challenge in concurrent programming
comes from the need to synchronize the
execution of different processes and to enable
them to communicate.
• If the processes were totally independent, the
implementation of concurrency would only
require a simple scheduler to allocate resources
among them.
95
96. • But if an I/O process accepts a character typed
on a keyboard, it must somehow communicate
it to the process running the word processor,
and if there are multiple windows on a display,
processes must somehow synchronize access
to the display so that images are sent to the
window with the current focus.
96
97. Multitasking
• Multitasking is a simple generalization from the
concept of overlapping I/O with a computation to
overlapping the computation of one program with
that of another.
• Multitasking is the central function of the kernel
of all modern operating systems.
• A scheduler program is run by the operating
system to determine which process should be
allowed to run for the next interval of time.
•
97
98. • The scheduler can take into account priority
considerations, and usually implements time-
slicing, where computations are periodically
interrupted to allow a fair sharing of the
computational resources, in particular, of the
CPU.
98
100. Process vs Thread
• The term process is used in the theory of concurrency, while
the term thread is commonly used in programming languages.
• The process runs in its own address space managed by the
operating system.
• The thread runs within the address space of a single process
and may be managed by a multithreading kernel within the
process.
•
100
101. The difference between Multitasking
and multithreading
• The basic difference between Multitasking and
multithreading is that Multitasking allows CPU
to perform multiple tasks (program, process, task,
threads) simultaneously.
• Whereas, Multithreading allows multiple threads
(a thread is a part of program) of the same process
to execute simultaneously.
101
102. Example
• Consider a simple web server
• The web server listens for request and serves it
• If the web server was not multithreaded, the requests
processing would be in a queue, thus increasing the
response time and also might hang the server if there
was a bad request.
• By implementing in a multithreaded environment, the
web server can serve multiple request simultaneously
thus improving response time
102
103. Multiple Computers
(Multi-processor)
• Multiprocessors are systems designed to bring the
computing power of several processors to work in
concert on a single computationally-intensive
problem.
• Multiprocessors are extensively used in scientific and
engineering simulation, for example, in simulating
the atmosphere for weather forecasting and studying
climate.
• The entire Internet can be considered to be one
distributed system working to disseminate
information in the form of email and web pages.
103
104. Multiple Computers (Multi-processor)
• The days of one large computer serving an entire
organization are long gone. Today, computers hide in
unforeseen places like automobiles and cameras.
• In your personal "computer" (in the singular) contains
more than one processor:
– the graphics processor is a computer specialized for the task of
taking information from the computer's memory and rendering
it on the display screen.
– I/O and communications interfaces are also likely to have their
own specialized processors.
104