0% found this document useful (0 votes)
15 views

Chapter Five

The document discusses logic programming and the Prolog language. It covers the differences between procedural and declarative languages, basics of Prolog including rules, variables, and structures, and provides examples of Prolog code including facts, rules, and queries.

Uploaded by

cybernetethiopia
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Chapter Five

The document discusses logic programming and the Prolog language. It covers the differences between procedural and declarative languages, basics of Prolog including rules, variables, and structures, and provides examples of Prolog code including facts, rules, and queries.

Uploaded by

cybernetethiopia
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 63

Chapter Five

Logic Programming:
Outlines

 Procedural Vs Declarative languages


 Programming basics
 Prolog rules
 Horn clauses, resolution, and Recursion
 Expert system
Procedural Vs Declarative languages
• Generally, there are two types of programming language
paradigms.
These are
1. Declarative programming language
 Specify what the situation (rules and
facts) and the goal (query) are.
 Determine what will be the output of the program.
Example: prolog
Procedural Vs Declarative languages
• Procedural languages
– specifying how to achieve a certain goal in a certain
situation.
– Determines how the output is obtained.

– Imperative programming language.

Example: C, Pascal, Java


Programming Basics
• Prolog (programming in logic) is one of the most widely used
programming languages in artificial intelligence research.
• It is a declarative programming language.
That means, when implementing the solution to a problem,
– instead of specifying how to achieve a certain goal in a
certain situation,
– we specify what the situation (rules and facts) and the goal
(query) are and let the Prolog interpreter derive the solution
for us.
Programming Basics
 Invented by Alain Colmerauer & his associate around 1970.

 Chosen for commuting:

 Relational databases

 Mathematical logic

 Understanding natural languages

 Artificial intelligence
Prolog
• Prolog is very useful in some problem areas, such as artificial
intelligence, natural language processing, databases, . . . , but
pretty useless in others, such as graphics or numerical algorithms.
• Prolog is a programming language for symbolic, non-numeric
computation.
• Suitable for solving problems that involve objects and relations b/n
objects. The arguments of relations can be concrete

Relation Name objects, or constants (such as tom and bob),or


general objects such as X and Y. Objects of the
parent( tom, bob).
Ar first kind in our program are called atoms.
gu
me
nt Objects of the second kind are called variables.
s
Con…
• Prolog is a declarative (or descriptive) language.
• Programming in prolog means describing the world.

• Using such program means asking prolog questions about

previously described world.


• Example: bigger(elephant, horse).
– Meaning, it is true(fact) that an elephant is bigger than a
horse.
Data objects
 Prolog provides only one data type, called a term.
 Term is central data structure in prolog.
 The Prolog system recognizes four types terms.
 These are:
 Atoms
 Numbers
 Variables and
 Structures
1. Atoms
• Atoms are strings of characters.
• Atoms and numbers are sometimes grouped together and called
atomic terms.
• Upper-case letters A,B,…,Z
• Lower-case letters a,b,..,z
• Digits 0,1,2…,9
• Special characters such as + -*/<>=;.&_~
Atoms & Numbers
– Atoms are usually strings made up of lower & uppercase
letters, digits, & underscore starting with lowercase letter.

Example:

elephant, b, abcXYZ, x_23, another_pint_for_me_please

– An atom which begin with a capital letter, a digit or “_”


must be quoted;

‘my mother’ ‘George, and, gertie’ ‘205’ ‘_first’ ‘George’


Strings of special characters:
Strings made up of solely special characters like
+ - * <---> ===> . . . ::= are atoms.
2. Number
• Numeric constants
• Includes
– Integers
205 -10
– Real numbers
3.75
Exercises
a) Which of the following are valid atoms:
i. b
ii. B
iii. an_extremely_long_sequence_of_characters
iv. 7
v. man(george)
vi. ‘man(george)’
Answer
i. b
ii. an_extremely_long_sequence_of_characters
iii. ‘man(george)’
3). Variables
 Variables are strings of letters, digits, & underscore, starting
with upper-case letter or an underscore character.
For Example: X, Result, Object2, Participant_list, ShopingList,
_x25, _23
 Variables are a place holder, denoting an specified value which
we wish prolog to fill in.
Example: haschild(X):-parent(X,Y).
soldier(aardvark, R).
Phrased in everyday English, the question is:
“What is Aardvark’s rank?”
Variables
 _ (single underscore) is a variable with special case.

 It is called anonymous variable.

 Used when the value of the variable is of no particular interest.

 Multiple occurrences of the anonymous variable in one


expression are assumed to be distinct, their values don’t
necessarily the same.

 Example: bigger(whale, _).


4). Structures
• Structured objects (structures)

• Called compound terms.

• Structured objects are made up of a functor (prolog atoms) and a


number of arguments(prolog term, i.e. atoms, numbers, variables or
other structures) enclosed by parenthesis & separated by commas.

• Has several components


• Example
• is_bigger(horse,X), f(g(X,_),7), ‘My Functor’(dog)

• date(day, month,year).
con…
• The set of compound terms and atoms together form set of
prolog predicates.
• A term that doesn't contain any variables is called a ground
term.
Clauses, Programs & Queries
• Prolog program consists of clauses.
• These are three types:
• Facts
• Rules and
• Questions.
Facts
 A Fact is a predicate followed by a dot.
 Meaning of fact is that certain instance of relation as being
true.
 Fact declares things that are always, unconditionally true.

Example: likes(john, mary).


 The names of all r/ships and objects must begin with a lower-
case letter.
 For example; likes, john , mary.
 At the end of a fact put a period “.”
Facts
soldier(peckem, general).
soldier(cathcart, colonel).
soldier(moodus, colonel).
soldier(towser, sergeant).
soldier(knight, sergeant).
soldier(aardvark, captain).
soldier(dunbar, lieutenant).
soldier(flume, captain).
soldier(danby, major).
Rules
• Rules: declare things that are true depend on the given
condition.
• Express a general principle governing the relationship between
objects, rather than just listing specific instances of a
relationship.
Example:
same_rank (A, B):-
soldier (A, R),
soldier (B, R).
Rule
• A rule has a head and a body, separated by the special
symbol :-, which is pronounced “if”.
• The body consists of one or more sub-goals, separated by
commas.
• For example:

same_rank (A, B) - - - - - - - - - - - - - - - is the head of the rule,


soldier (A, R), soldier (B, R). - - - - - - - - is the body of the rule,
soldier (A, R) - - - - - - - - - - - - - - - is the first sub-goal,
soldier (B, R) - - - - - - - - - - - - - - - is the second sub-goal.
Meaning
 “It is true that: soldier A holds the same rank as soldier B if it is
true that:
soldier A holds rank R and it is true that: soldier B holds rank
R.”
Con…
• Programs. A Prolog program is a sequence of
clauses.
Question
• Question: users can ask the program what things are true.

• A question has the form of a structure, preceded by the


symbol ?- and terminated by a full-stop.
example:
?- soldier (towser, sergeant).
Interpretation: “Is there a soldier Towser with the rank of
sergeant?”
Prolog clauses consist head and body.
Con…
 The body is the list of goals separated by commas. Commas are
understood as conjunctions.
 Facts are clauses that have a head and empty body.
 Questions only have the body.
 Rules have the head and non-empty body.
 In prolog, variables are universally quantified and read as “For all”.
 Example: haschild(X):-parent(X,Y). , Can be read in two ways:

 For all X and Y, If X is parent of Y then X has child.


 For all X, X has child if there is some Y such that X is a parent of Y.
The gist of Prolog
 Some facts about Prolog:
 Prolog is a high-level logic programming language
(PROgramming in LOGic);
 Good at pattern matching (by unification) and
searching;
 Not very good for repetitive number crunching;
 Excellent for language processing, rule-based
expert systems, planning and other AI applications;
 Uses depth-first search and backtracking to search for
solutions automatically;
 Best written in little chunks (modular code): indeed this is
assumed in its syntax;
 Uses a % to prefix comments or /* ... */ to surround them.
 The three most important concepts in Prolog are
unification, backtracking and recursion.
 If you understand these concepts thoroughly you can
probably write pretty good Prolog programs.
 Unification is one in which two uninstantiated variables are
unified.
 The way in which Prolog matches two terms is called
unification.
 Example:
X = 5.0

 Given two terms T1 and T2 which are to be unified:


 If T1 and T2 are constants (i.e., atoms or numbers) then if
they are the same succeed. Otherwise fail.
 If T1 is a variable then instantiate T1 to T2.
ARITHMETIC

 is, which takes an expression (on the right), evaluates it,


and unifies the result with its argument on the left;
 =:=, which evaluates two expressions and compares the
results;
 =, which unifies two terms (which need not be
expressions, and, if expressions, will not be evaluated).
Matching
 Matching is an operation on terms. Two terms match if:
 they are identical, or
 The variables in both terms can be instantiated to objects,
after the substitution of variables by these objects the
terms become identical.
 date(D,M,1995) matches date(D1,may,Y1)
 If matching succeeds it always results in the most general
instantiation possible.
 date(D,M,1995) = date(D1,may,Y1).
D = D1
M=may
Y1=1995
OUTPUT: write, nl, display
 The built–in predicate write takes any Prolog term as its

argument, and displays that term on the screen.

 The built–in predicate nl, with no arguments, advances to a

new line. For example:


 ?- write('Hello'), write('Goodbye').
HelloGoodbye
yes
 ?- write('Hello'), nl, write('Goodbye').
Hello
Goodbye
yes
Con…

 Writeq is used to display strings with quotes.


 ?- writeq('hello there').
'hello there'
yes
 Another predicate, called display, puts all functors in front of
their arguments even if they were originally written in other
positions.
 This makes display useful for investigating the internal
representation of Prolog terms. For example:
?- display(2+2).
+(2,2)
yes
INPUT OF TERMS: read
 The built–in predicate read accepts any Prolog term
from the keyboard.
 That term must be typed in the same syntax as if it
were within a Prolog program, and it must
be followed by a period. For example:
?- read(X).
hello. (typed by user)
X = hello
yes
Con…
 This shows that + is an infix operator. 2+2 does not represent
the number 4; it is a data structure consisting of a 2, a +, and
another 2.
 Still another predicate, write_canonical, combines the effects
of writeq and display:
?- write_canonical(2+3).
+(2,3)
?- write_canonical('hello there').
'hello there‘
 Otherwise, If T2 is a variable then instantiate T2 to T1.
 If T1 and T2 are complex terms with the same arity
(number of arguments), find the principal functor F1 of T1
and principal functor F2 of T2. If these are the same, then
take the ordered set of arguments of hA1, · · · , AN of T1
and the ordered set of arguments hB1, . . . , BN of T2. For
each pair of arguments AM and BM from the same position

in the term, AM must unify with BM.


Con…
• Prolog process to make two terms equal by
assigning variables in one term to values at the
corresponding location of the other term. For
example:
?- foo(a, B) = foo(A, b).
A = a,
B=b
Unlike assignment (which does not exist in Prolog),
unification is not directed.
Backtracking using Fail

 The built–in predicate fail always fails; you can use it to force
other predicates to backtrack through all solutions.

 ?- capitals(State,City),write(City), tab(1), write('is the capital


of'), tab(1),write(State),nl,fail.
Recursion
 Recursion is
Something that is defined in terms of “smaller
versions” of itself.
 Repetition is expressed in Prolog by using
RECURSION, a program structure in which a
procedure calls itself.
Example
member(X,[X|_]). % Clause 1
Now for the recursive part. Think about this carefully
to see why it works:
X is a member of Y if X is a member of the tail of Y.
This is expressed in Prolog as follows:
member(X,[_|Ytail]) :- member(X,Ytail). % Clause 2
Simple goals
 Prolog is sent into action by giving it a goal.

 Simple Prolog commands are formed by a name (the


predicate name), followed by brackets round the data
item(s) involved (the arguments).
 The Prolog command for simple printing is write.
 Write(‘Hello’).

The output is: Hello

true
Con…
• Prolog generally prints true when it has
successfully completed a command, and false if it
fails to.
Conjoining commands

 Several commands can be typed one after another,

provided commas are put between them (and a full stop

after the last one). For example

write(’hello’), nl, write(’master’).

 Here, nl is a built-in procedure which causes a new


line to be output.
Con…
• Another built-in command is tab, which puts out a given
number of spaces. Try:
?- write('oh'),tab(3),write('what'), tab(3), write('a'),tab(3),
write('beautiful'),tab(3), write('morning').
Output:
oh what a beautiful morning
true.
Lists
 Lists are a special class of compound term. They are
represented in Prolog as either:
 The atom [], representing the empty list.
 A compound term with functor ‘.’ and two arguments
representing respectively the head and tail of the list. The
tail argument must, itself be a list (possibly empty).
Some Built-in Predicates for List Manipulation

• Prolog comes with a range of predefined predicates for


manipulating lists. Some of the most important ones are
presented here,
length/2: The second argument is matched with the length of the
list in the first argument. Example:
?- length( [elephant, [], [1, 2, 3]], Length).
Length = 3
Con…
• It is also possible to use length/2 with an uninstantiated first
argument.

• This will generate a list of free variables of the specified


length:
?- length( List, 3).
List = [_G248, _G251, _G254]

– The names of those variables will be different every time


you call this query, because they are generated by Prolog
during execution time.
member/2

• member/2: The goal member( Elem, List) will succeed, if the


term Elem can be matched with one of the members of the list.
Example:
?- member( dog, [elephant, horse, donkey, dog, monkey]).
Yes
append/3

• append/3: Concatenate two lists. This built-in works


exactly like the predicate
last/2: This predicate succeeds, if its first argument
matches the last element of the list given as the
second argument of last/2.
reverse/2

• reverse/2: This predicate can be used to reverse the order of


elements in a list.
• The first argument has to be a (fully instantiated) list and the
second one will be matched with the reversed list.
• Example:
?- reverse( [1, 2, 3, 4, 5], X).
X = [5, 4, 3, 2, 1]
select/3

• select/3: Given a list in the first argument and an element of


that list in the second, this predicate will match the third
argument with the remainder of that list.
Example:
?- select(bird,[mouse, bird, jellyfish, zebra], X).
X = [mouse, jellyfish, zebra]
FILE HANDLING: see, seen, tell, told

 The built–in predicate see takes a filename as an


argument.
 It opens that file for input (if it is not already open)
and causes Prolog to take input from that file rather
than from the keyboard.
 The predicate seen closes all input files and switches
input back to the keyboard.
Example
• tell(‘myfile’),
write(green(kermit)), write('.'), nl,
write(green(asparagus)), write('.'), nl,
told.

• ?- see('mydata'),
read(X),
read(Y),
read(Z),
seen.
• The predicate tell opens a file for output and switches
output to that file; told closes output files and
switches output back to the console.
CHARACTER INPUT AND OUTPUT: get, get0, put

• The built–in predicate put outputs one character; its argument


is an integer that gives the character’s ASCII code. For
example:
?- put(42).
*
yes
• The opposite of put is get. That is, get accepts one character
and instantiates its argument to that character’s ASCII code,
like this:
?- get(X).
* (typed by user)
X = 42
 If you want to read every keystroke that comes in, or every
byte in a file, use get0 instead. For example, if you type
?- get0(X), get0(Y).
Expert systems
 Prolog logic programming languages, that gather a database of facts and

rules about some domain and then use the database to draw conclusions.

Such programs are known as expert systems, knowledge-based systems,

or rule-based systems.

 The database in an expert system attempts to capture the knowledge

(“elicit the expertise”) of a human expert in a particular field, including

both the facts known to the expert and the expert’s reasoning path in

reaching conclusions from those facts. The completed expert system not

only simulates the human expert’s actions but can be questioned to reveal

why it made certain choices and not others.


Con…
 Expert systems have been built that simulate a medical
specialist’s diagnosis from a patient’s symptoms, a factory
manager’s decisions regarding valve control in a chemical
plant based on sensor readings, the decisions of a fashion
buyer for a retail store based on market research, the choices
made by a consultant specifying a computer system
configuration based on customer needs, and many more.
 The challenging part of building an expert system lies in
extracting all pertinent facts and rules from the human expert.
STATIC AND DYNAMIC PREDICATES
 Dynamic predicates can be asserted and retracted.

 Static predicates cannot, because their clauses have been compiled into a
form that runs faster but is no longer modifiable at run time.
 Dynamic declarations have another effect, too: they tell the Prolog system
not to worry if you try to query a predicate that doesn’t exist yet.
• Assertz, asserta: permanent way of storing information.

asserta(Clause): Adds Clause at the beginning of the clauses for its

predicate.

• If there are no clauses for that predicate, the predicate is created and

declared to be dynamic.

If the predicate already has some clauses and is static, an error condition is

raised.

assertz(Clause): Like asserta, but adds the clause at the end of the other

clauses for its predicate.


• retract(Clause): Removes from the knowledge base a dynamic clause
that matches Clause (which must be at least partly instantiated).
• abolish(Functor/Arity):Completely wipes out the dynamic predicate
designated by Functor/Arity, as if it had never existed.
• Its dynamic declaration is forgotten, too, and current_predicate no
longer recognizes it.

You might also like