An Introduction To Prolog

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 18

An introduction to Prolog

Programs and Questions

A program in Prolog is simply a knowledge base (KB) of true sentences and facts. The
knowledge base is written in a separate file and loaded into Prolog with the command:
[filename].
The square brackets and period are necessary.

Once the program/KB is loaded you ask questions of Prolog, which it answers by backward
chaining through the KB.
Questions are presented as sentences. Prolog answers yes or no and lists any substitutions it
made to make the query true.

Note that yes means the sentence is true given Prolog's current KB (and the required
substitutions). However, no only means that the sentence cannot be proven with Prolog's current
KB

Example:
The program/KB is
parent(bob, joe).
parent(bob, tim).
parent(sue, joe).
parent(joe, sally).

We can ask questions like:


parent(sue, joe).
And the response will be
Yes

Or we could ask
parent(X, joe).
Prolog will respond
X = bob and pause. Type a semicolon and Prolog will continue with
X = sue and pause again. Type a semicolon again and Prolog will continue with
No. There are no more substitutions that make parent(x, joe) true.

If we ask
parent(bob, sally).
Prolog will respond
No

You can also ask compound questions (using a comma for AND and a semicolon for OR). The
question:
parent(X,tim), parent(X,joe).
gives
X = bob ; (the user types the semicolon)
No

The question:
parent(X,tim); parent(X,sally).
Gives
X = bob ;
X = joe ;
No

Basic syntax

Implication and Clauses

In Prolog implies is written as :- and is read from right to left.


The universal quantifier is assumed for all variables and a comma is used for AND.
Example:
 x Cat(x)  Tame(X)  Pet(x) would be written as

pet(X) :- cat(X),tame(X).

Sentences are apparently written 'backwards' to reflex the fact that Prolog uses backwards
chaining. Thus, the above sentence could be read as ‘to prove that X is a pet prove that X is a cat
and that X is tame.
(Note sentences in Prolog end in a period. Variables must start with a capital letter or an
underscore and objects and relations begin with a lower-case letter.)
A semicolon is used for OR.
Example:
 x Cat(x)  Tiger(x)  Predator(x) would be written as
predator(X) :- cat(X);tiger(X).

However, sentences using an OR are normally written as two separate sentences.


predator(X) :- cat(X).
predator(X) :- tiger(X).

Sentences must be Horn clauses, that is each sentence must be an atomic sentence or an
implication with an atomic consequence.

Naming relationships, properties and objects

Relationships, properties and objects must be strings of letters, digits, and underscores beginning
with a lower case letter. Examples: bob, dog1, x_7, isA, parentOf.
Strings of characters in single quotes are used if you want to begin with an upper case letter.
Examples: 'Bob', 'Sue'<ca’< p=""> </ca’<>

For relations and properties the name of the relationship or property is given first, with the
object, or objects, in parentheses and separated by commas.
Examples: isA(dog1,animal), isFurry(cat).
Objects- dog1, cat, animal
Relationship- is Property- isFurry

The programmer decides on the meaning, the semantics, of the relationships and properties.
Typically a relationship like relation(X,Y) is read X is relation to/of/for Y.

Variables

Variables are strings of letters, digits, and underscores beginning with an upper-case letter or an
underscore. Examples: X, Answer, _X, _Y7.

Variables that are only used in a clause once can be replaced by an underscore. Two underscores
in a clause are not matched.
Example:
hasAChild(X) :- parent(X,_) If X is a parent of anyone, then X has a child.

Advanced Programs and Questions

Consider the KB given in the first section:


parent(bob, joe).
parent(bob, tim).
parent(sue, joe).
parent(joe, sally).
For this KB to be useful we need more general rules than simply X is the parent of Y. For
example, we might add to our KB:
offspring(X,Y) :- parent(Y,X).
which can be read as
 X,Y parent(Y,X)  offspring(X,Y)
or as
Y is the parent of X implies that X is the offspring of Y.

Now if we ask:
offspring(X, bob).
Prolog gives
X = joe ;
X = tim ;
No

Remember that implication is only one way, even if it appears that it should work both ways.
Consider the following KB:
offspring(X,Y) :- parent(Y,X).
offspring(bob, mary). '‘bob is th eoffspring o mary.' If we ask Prolog:
parent(X,bob).
It responds
No
Prolog knows that a parent relationship implies an offspring relationship, but the opposite is not
necessarily true.

For example:
mammal(X) :- cat(X).
X is a cat implies X is a mammal is true, but the opposite is not necessarily true.

Facts, Rules and Queries


Symbols

Prolog expressions are comprised of the following truth-functional symbols, which have the
same interpretation as in the predicate calculus.

English Predicate Calculus PROLOG


and ^ ,
or v ;
if --> :-
not ~ not

Variables and Names


Variables begin with an uppercase letter. Predicate names, function names, and the names for
objects must begin with a lowercase letter. Rules for forming names are the same as for the
predicate calculus.
mother_of
male
female
greater_than
socrates

Facts

A fact is a predicate expression that makes a declarative statement about the problem domain.
Whenever a variable occurs in a Prolog expression, it is assumed to be universally quantified.
Note that all Prolog sentences must end with a period.
likes(john, susie). /* John likes Susie */
likes(X, susie). /* Everyone likes Susie */
likes(john, Y). /* John likes everybody */
likes(john, Y), likes(Y, john). /* John likes everybody and everybody
likes John */
likes(john, susie); likes(john,mary). /* John likes Susie or John likes Mary
*/
not(likes(john,pizza)). /* John does not like pizza */
likes(john,susie) :- likes(john,mary)./* John likes Susie if John likes Mary.

Rules

A rule is a predicate expression that uses logical implication (:-) to describe a relationship
among facts. Thus a Prolog rule takes the form
left_hand_side :- right_hand_side .

This sentence is interpreted as: left_hand_side if right_hand_side. The left_hand_side is


restricted to a single, positive, literal, which means it must consist of a positive atomic
expression. It cannot be negated and it cannot contain logical connectives.

This notation is known as a Horn clause. In Horn clause logic, the left hand side of the clause is
the conclusion, and must be a single positive literal. The right hand side contains the premises.
The Horn clause calculus is equivalent to the first-order predicate calculus.

Examples of valid rules:

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 */

Examples of invalid rules:

left_of(X,Y) :- right_of(Y,X) /* Missing a period */


likes(X,Y),likes(Y,X) :- friends(X,Y). /* LHS is not a single
literal */
not(likes(X,Y)) :- hates(X,Y). /* LHS cannot be negated */

Queries

The Prolog interpreter responds to queries about the facts and rules represented in its database.
The database is assumed to represent what is true about a particular problem domain. In making
a query you are asking Prolog whether it can prove that your query is true. If so, it answers "yes"
and displays any variable bindings that it made in coming up with the answer. If it fails to prove
the query true, it answers "No".

Whenever you run the Prolog interpreter, it will prompt you with ?-. For example, suppose our
database consists of the following facts about a fictitious family.

father_of(joe,paul).
father_of(joe,mary).
mother_of(jane,paul).
mother_of(jane,mary).
male(paul).
male(joe).
female(mary).
female(jane).

We get the following results when we make queries about this database. (I've added comments,
enclosed in /*..*/, to interpret each query.)

Script started on Wed Oct 01 14:29:32 2003


sh-2.05b$ gprolog
GNU Prolog 1.2.16
By Daniel Diaz
Copyright (C) 1999-2002 Daniel Diaz
| ?- ['family.pl'].
compiling /home/ram/public_html/cpsc352/prolog/family.pl for byte code...
/home/ram/public_html/cpsc352/prolog/family.pl compiled, 9 lines read - 999
bytes written, 94 ms

(10 ms) yes


| ?- listing.

mother_of(jane, paul).
mother_of(jane, mary).

male(paul).
male(joe).

female(mary).
female(jane).

father_of(joe, paul).
father_of(joe, mary).

(10 ms) yes


| ?- father_of(joe,paul).

true ?

yes
| ?- father_of(paul,mary).

no
| ?- father_of(X,mary).

X = joe

yes
| ?-
Prolog interruption (h for help) ? h
a abort b break
c continue e exit
d debug t trace
h/? help

Prolog interruption (h for help) ? e


sh-2.05b$ exit

script done on Wed Oct 01 14:30:50 2003

Closed World Assumption. The Prolog interpreter assumes that the database is a closed world
-- that is, if it cannot prove something is true, it assumes that it is false. This is also known as
negation as failure -- that is, something is false if PROLOG cannot prove it true given the facts
and rules in its database. In this case, in may well be (in the real world), that Paul is the father of
Mary, but since this cannot be proved given the current family database, Prolog concludes that it
is false. So PROLOG assumes that its database contains complete knowledge of the domain it is
being asked about.

Prolog's Proof Procedure

In responding to queries, the Prolog interpreter uses a backtracking search, similar to the one
we study in Chapter 3 of Luger. To see how this works, let's add the following rules to our
database:
parent_of(X,Y) :- father_of(X,Y). /* Rule #1 */
parent_of(X,Y) :- mother_of(X,Y). /* Rule #2 */

And let's trace how PROLOG would process the query. Suppose the facts and rules of this
database are arranged in the order in which they were input. This trace assumes you know how
unification works.

?- parent_of(jane,mary).
parent_of(jane,mary) /* Prolog starts here and searches
for a matching fact or rule. */
parent_of(X,Y) /* Prolog unifies the query with the rule #1
using {jane/X, mary/Y}, giving
parent_of(jane,mary) :- father_of(jane,mary) */
father_of(jane,mary) /* Prolog replaces LHS with RHS and searches. */
/* This fails to match father_of(joe,paul) and
and father_of(joe,mary), so this FAILS. */
/* Prolog BACKTRACKS to the other rule #2 and
unifies with {jane/X, mary/Y}, so it matches
parent_of(jane,mary) :- mother_of(jane,mary) */
mother_of(jane,mary) /* Prolog replaces LHS with RHS and searches. */

YES. /* Prolog finds a match with a literal and so


succeeds.

Here's a trace of this query using Prolog's trace predicate:

| ?- trace,parent_of(jane,mary).
{The debugger will first creep -- showing everything (trace)}
1 1 Call: parent_of(jane,mary) ?
2 2 Call: father_of(jane,mary) ?
2 2 Fail: father_of(jane,mary) ?
2 2 Call: mother_of(jane,mary) ?
2 2 Exit: mother_of(jane,mary) ?
1 1 Exit: parent_of(jane,mary) ?

yes
{trace}
| ?-

Exercises

1. Download the family.pl file.


2. Add a male() rule that includes all fathers as males.
3. Add a female() rule that includes all mothers as females.
4. Add the following rules to the family database:
5. son_of(X,Y)
6. daughter_of(X,Y)
7. sibling_of(X,Y)
8. brother_of(X,Y)
9. sister_of(X,Y)
10. Given the addition of the sibling_of rule, and assuming the above order for the facts
and rules, show the PROLOG trace for the query sibling_of(paul,mary).

C463 / B551 Artificial Intelligence

Knowledge Representation

Knowledge Representation

 A knowledge representation (KR) is a surrogate, a substitute for the thing itself, used to
enable an entity to determine consequences by thinking rather than acting, i.e., by
reasoning about the world rather than taking action in it.
 It has three components: (i) the representation's fundamental conception of intelligent
reasoning; (ii) the set of inferences the representation sanctions; and (iii) the set of
inferences it recommends.
 It is a medium for pragmatically efficient computation, providing guidance for organizing
information to facilitate making inferences.
 It is a medium of human expression, i.e., a language in which we say things about the
world.

KR As Surrogate

 A stand-in for things that exist in the world.


 It is a component of the reasoning system.
 The representation stands for something in the real world
 there must be a connection between them
 this defines the semantics or meaning of the representation.
 How close is a representation to the represented object? Which properties of the object
should be present in the representation and which can be omitted?
 Representations are imperfect: they contain simplifying assumptions and maybe artifacts.

Ontological Engineering

 Ontology - branch of philosophy studying entities that exist, their classification, and the
relations between them.
 Types of entities: physical objects, abstract objects, time, locations, actions, events,
beliefs.
 Decisions made on imperfect representations can be wrong. We must choose the
representation with this in mind.
 Selecting a particular representation means making an ontological commitment.

Ontology Example

KB and Database

 The KB in a program can be represented as a relational database.


 The larger the KB, the better its structure must be thought from the start.
 The database should be consistent in terms of connectivity - if something changes in one
place, the change must be reflected everywhere else.
 The database must be unified, meaning that we must be able to use its various
components within the same framework. A particular application may require more than
1 component.

Expert Systems

 Programs that incorporate knowledge of a particular domain and that can help with
making decisions.
 They often emerge from the retirement of a human expert that takes time and effort to
replace.
 Basic components: a knowledge base KB and an inference system.
 The expertise is organized in rules of type "if-then" by a human expert.
 For classification/diagnosis problems this often results in a tree.

General Functionality

 The user seeks a diagnosis or goal (car failure).


 The system asks a question, often with a yes/no answer.
 If this answer is not sufficient to determine the diagnosis completely, another question
will be asked.
 Some of the systems can allow for an undetermined answer (I don't know) and they can
adapt to that,
 The answer might be given with a certain probability.
 In general they avoid asking for irrelevant input.
Example - Car Classification

Semantic Networks

 A graph notation for representing knowledge. The nodes are concepts and the edges are
relations between them.
 Definitional networks - the relations are subtype or is-a.
 Assertional networks are designed to assert propositions.
 Implicational networks use implication to connect nodes.
 Executable networks can include procedures.
 Learning networks build or extend their representations by acquiring knowledge from
examples.
 Hybrid networks combine two or more of the previous techniques.
Example - Definition Network

Categories and Objects

 Organizing the objects in categories.


 Some reasoning takes places at the level of categories.
 "I want to eat an apple."
 Apple(x), or Member(x, Apple) and Subset(Apple, Food).
 The categories form a hierarchy where each class inherits the properties of the parent, or
simply a network (apples are both food and fruit).
 The categories of a class compose a taxonomy.

Partitioning

 Two or more categories are disjoint if they are mutually exclusive (male/female).
 A decomposition of a class into categories is called exhaustive if each object of the class
must belong to at least one category
 living = {animal, vegetable, fungi, bacteria}
 A partition is a an exhaustive decomposition of a class into disjoint subsets.
 student = {undergraduate, graduate}
 Related problem: clustering. Given a set of objects, find an appropriate category for each
of them. The categories may not be predefined.

Attributes

 Composition: PartOf(nose, face).


 Some categories can be defined as rules:
 Biped(x) => b1, b2 (Leg(b1) & Leg(b2) & PartOf(b1, x) & PartOf(b2, x) & !equal(b1,
b2).
 Prime(n) <=> (Number(n) & n != 1 & d (equal(n%d, 0) => (equal(d, 1) | (equal(d, n))))
 Measurements: Length(x), Price(x), etc. These are functions, not predicates.
 Things: 3 apples. Stuff: water, more water, some quantity of water.

Situations

 Situation: a predicate that is true at a particular moment in time. They may also have a
specific location. A particular state of the system.
 Drives(Mary, car, I90, 03/15/096)
 Fluent: predicates and functions that can change from a moment to another. Happy(x).
 Atemporal or eternal predicates: Warrior(A) will be true for as long as the object A
exists. Alive(A) may change from a moment to the next.

Actions

 Predicates that represent changes in the environment. The involve at least a subject, often
one or more objects.
 eat(x, y), sleep(x), talk(x), say(x, y)
 When an action is part of a situation, it can result in other predicates becoming true at a
later moment in time.
 (Eat(x, y, t) & Apple(y)) => !Hungry(x, t+1)
 Projection: the agent can use some rules to predict the outcome of its possible actions and
choose the appropriate one. This is done by planning.

Situation Calculus

 Description of an action:
 Possibility rule (precondition): a sentence that specifies when an action is possible.
 has(x, y, s) & apple(y) => Possible(eat(x, y), s)
 Effect rule (postcondition): a sentence that describes the consequences of an action.
 eat(x, y, s) => !exist(y, s+1)
 collect(x, y, s) => has(x, y, s+1)
 Frame problem: the collection of things / predicates that don't change.

Time and Events

 In time-based calculus the fluents are valid for particular moments in time instead of in a
particular situation.
 A fluent is true at a particular point in time if it was initiated or caused by an event in the
past, and was not terminated by another event in the meantime.
 Initiates(e, f, t), e-event, f-fluent, t-time.
 Terminates(e, f, t). Happens(e, t). Clipped(f, t, t2)
 T(f, t2) <=> e, t (Happens(e, t) & Initiates(e, f, t) & (t < t2) & !Clipped(f, t, t2) )
 Clipped(f, t, t2) <=> e, t1 (Happens(e, t1) & Terminates(e, f, t1) & (t < t1) & (t1 < t2) )

Mental Processes

 Does an agent know that he knows something?


 We need to represent the fact that an agent believes something to be true or knows
something to be true.
 We can make inferences about things an agent believes, things that the agent knows, and
things that are true, but the combinations are not always possible.
 The inferences can be made only if the agent is a logical agent capable of reasoning.
 This is called modal logic.

Beliefs

 Believes(x, P(a)) x believes that P(a) is true.


 Inferences are not obvious.
 Believes(x, P(a)) & (a = b) does not imply that Believes(x, P(b)) is also true.
 We can apply reasoning within the system of beliefs for a logical agent:
 Believes(x, P(a)) & Believes(x, P(y) => Q(y)) can imply that Believes(x, Q(a)).
 We can't apply MP if the agent doesn't know or believe that P(y) => Q(y).

Knowledge and Belief

 Knows(x, P(a)) is similar to Believes, but the fact P(a) must be true.
 KnowsWhether(x, P(a)) means Knows(x, P(a)) | Knows(x, !P(a)).
 KnowsWhat(x, EyeColor(a)) means that y Color(y) & Knows(x, (EyeColor(a) = y)).
 Believes(x, P(a)) & Knows(x, P(y)=>Q(y)) implies Believes(x, Q(a)).
 Knows(x, P(a)) & Believes (x, P(y)=>Q(y)) implies Believes(x, Q(a)).
 Knows(x, P(a)) & Knows(x, P(y)=>Q(y)) implies Knows(x, Q(a)).

Fuzzy Logic

 First author: Lotfi Zadeh, University of California at Berkley, 1965.


 Def. Part of logic dealing with approximate reasoning, derived from the fuzzy set theory.
 A fuzzy set is one to which elements belong with a given percentage.
 In fuzzy logic the truth values belong to the interval [0, 1] representing a percentage of
truth.
 It is better suited to represent imprecise information/attributes from the real world and to
make appropriate inferences.

Fuzzy Logic Expressions

 Classic logic: "Bill is a tall person."


 Tall(Bill) or Attribute(Bill, Tall) or
 in terms of sets, Bill belongs to TallPeopleSet
 Fuzzy logic: "Bill is 80% tall."
 Tall(Bill) = 0.8 or
 Bill belongs to TallPeopleSet by 80%
 We can also describe Bill as "quite tall" (80%) or "very tall"(95%) or "almost tall" (60%).
 It can apply to any comparable attributes:
 "Bill is taller than John."
 Tall(Bill) > Tall(John)

Hedges

 Hedges were introduced by Zadeh (MIT/IBM) and Lakoff (Berkley) in fuzzy logic and
represent modifier to fuzzy sets:
 All-purpose: very, quite, extremely
 Truth values: quite true, mostly false
 Probabilities: likely, not very likely
 Quantifiers, most, several, few
 Possibilities, like almost impossible, quite possible.

Examples of Deductions

 This stream is narrow.


 This stream and that stream are approximately equal.
 Thus, that stream is more or less narrow.
 Most men are vain.
 Socrates is a man.
 Thus, Socrates is most likely vain.

FL Versus Probabilities

 Classic logic: "The pony is pretty."


 Either True or False.
 Fuzzy logic: "The pony is 90% pretty."
 This means that about 90% of the people looking at the pony will think it's pretty. We're
talking about one particular pony.
 Probabilities: "The pony has 90% chances to be pretty."
 This means that for the given population of ponies in our model, 90% of them are pretty.
So 9 out of 10 ponies picked at random are expected to be pretty.

Operators

 Zadeh operators:
 or - value(A | B ) = max{value(A), value(B)}
 and - value(A & B) = min{value(A), value(B)}
 not - value(!A) = 1-value(A)
 Example: Annie is 90% tired and 75% cranky. Then Annie is
 90% tired or cranky,
 75% tired and cranky,
 10% rested, and
 25% is in a good mood.
 Other more complex metrics are also available.

Applications

 Automobile subsystems, such as ABS and cruise control


 Microcontrollers, microprocessors, robotics.
 Air conditioners, cameras, dishwashers, elevators.
 Search engines (web)
 The MASSIVE engine used in the Lord of the Rings films to create huge scale armies
with random but somewhat orderly movements
 Digital image processing, edge detection.
 AI agents for games
 Language filters on message boards for filtering out offensive text.

Fuzzy Controller

 A controller using fuzzy values for variables and rules like


 IF variable IS value THEN action
 The rules are not mutually exclusive.
 Example: controller for an air conditioner:
 IF temperature IS very cold THEN stop fan
 IF temperature IS cold THEN turn down fan
 IF temperature IS normal THEN maintain level
 IF temperature IS hot THEN speed up fan
Example of Fuzzy Sets - car speed

Fuzzy Controller Structure

Example of Fuzzification - car speed


Defuzification Example

 Rule1: If the car is slow then increase the speed by 10.


 Since we got a 0.75% slow -> +10*0.75
 Rule2: If the car is fast, then decrease the speed by 10.
 Fuzzy value for fast = 0.25 => -10*0.25.
 Crisp answer:
(10*0.75 – 10*0.25)/(0.75+0.25) = +5

You might also like