An Introduction To Prolog
An Introduction To Prolog
An Introduction To Prolog
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).
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
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).
Sentences must be Horn clauses, that is each sentence must be an atomic sentence or an
implication with an atomic consequence.
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.
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.
Prolog expressions are comprised of the following truth-functional symbols, which have the
same interpretation as in the predicate calculus.
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 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.
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.)
mother_of(jane, paul).
mother_of(jane, mary).
male(paul).
male(joe).
female(mary).
female(jane).
father_of(joe, paul).
father_of(joe, mary).
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
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.
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. */
| ?- 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
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
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
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
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
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
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.
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
Beliefs
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
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
FL Versus Probabilities
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
Fuzzy Controller