\documentstyle[a4,alltt]{article}
 
 
\topmargin 0.9 in         %   Nominal distance from top of paper
                          %   to top of page - 1in
\textheight 7.3 in        %   Height of body of page
\textwidth  5.25 in       %   Width of text area
\oddsidemargin  0.5 in    %   (Left margin on odd-numbered pages-1in)
\evensidemargin 0.5 in    %   (Left margin on even-numbered pages-1in)
\marginparwidth 1 in      %   Width of marginal notes.
\parindent 0.25 in        %   Amount of indent on first line of para
 
\begin{document}
 
\newcommand{\idx}[1]{}
\newcommand{\B}[0]{{\char92}}
 
\title{Supplement 4}
\author{Jocelyn Ireson-Paine}
\maketitle
 
 
\section{Introduction}
 
Because the best way to learn a language is to immerse yourself in it,
this supplement is larger than the others, and shows Prolog at work in a
number of different situations. The final section introduces a trading
game, in which the aim is to program an automatic trader to buy and sell
so as to make the greatest possible profit. This is open-ended; the game
itself can be extended in many ways, while building truly adaptable
traders involves a number of principles from A.I.
 
As you work through this, please bear in mind the logical meaning of
each Prolog clause you encounter. If you have any difficulty
understanding it, try applying the translation rules given in Lesson 4,
either mentally or by calling \verb#analyse#.\idx{analyse@\verb#analyse# command|ee}
 
Before doing this supplement, make sure your Tutor is in Prolog mode,
using the \verb#prolog# command.
 
 
\section{Classifying animals (PP)}
 
This section introduces a simple animal classifier\idx{animal classifier|ee}. Please start by
restoring the \verb#animals#\idx{ANIMALS|ee} knowledge base, and make a printed copy of it.
 
The classifier is similar to the ski advisor\idx{ski advisor|ee} of Supplement 1, but unlike
the
latter, it contains some {\it unary} (one-argument) predicates\idx{predicates!unary|ee}, such as
\verb#gives_milk#\idx{gives\_milk/1@\verb#gives_milk/1#|ee} and \verb#flies#\idx{flies/1@\verb#flies/1#|ee}. There are none
with more than two arguments, but you will see some of these later, in
the trading game.
 
A complete list of predicates follows. After each, I have stated what I
intend it to mean. For example, from the description of \verb#spots#\idx{spots/2@\verb#spots/2#|ee} below,
you can see that the fact
\begin{verbatim}
    spots( pip, black ).
\end{verbatim}
means Pip has black spots.
 
\begin{itemize}
 
\item \verb#chews_cud(A)#\idx{chews\_cud/1@\verb#chews_cud/1#|ee}: A is an animal which chews its cud.
 
\item \verb#colour(A,C)#\idx{colour/2@\verb#colour/2#|ee}: A is an animal whose colour is C (\verb#black#,
\verb#black_and_white#, or \verb#tawny#).
 
\item \verb#eats(A,F)#\idx{eats/2@\verb#eats/2#|ee}: A is an animal that eats food type F
(\verb#grass# or \verb#meat#).
 
\item \verb#eye_direction(A,D)#\idx{eye\_direction/2@\verb#eye_direction/2#|ee}: A is an animal whose eyes point in direction
D (\verb#forward# or \verb#sideways#).
 
\item \verb#flies(A)#\idx{flies/1@\verb#flies/1#|ee}: A is an animal that can fly.
 
\item \verb#gives_milk(A)#\idx{gives\_milk/1@\verb#gives_milk/1#|ee}: A is an animal that gives milk.
 
\item \begin{sloppypar}
\verb#has(A,P)#\idx{has/2@\verb#has/2#|ee}: Animal A has body part P (\verb#claws#, \verb#feathers#, \verb#hair#,
\verb#hoofs#, or
\verb#pointed_teeth#).
\end{sloppypar}
 
\item \verb#is_a(C1,C2)#\idx{is\_a/2@\verb#is_a/2#|(ee}:
Class C1 of animals is included in class C2. The
names of classes (including the animals themselves) are
\verb#albatross#, \verb#animal#, \verb#bird#, \verb#carnivore#, \verb#cheetah#, \verb#giraffe#,
\verb#mammal#, \verb#ostrich#, \verb#penguin#, \verb#tiger#, \verb#ungulate# and \verb#zebra#.
\idx{is\_a/2@\verb#is_a/2#|)ee}
 
\item \verb#lays_eggs(A)#\idx{lays\_eggs/1@\verb#lays_eggs/1#|ee}: Animal A lays eggs.
 
\item \verb#long_legs(A)#\idx{long\_legs/1@\verb#long_legs/1#|ee}: Animal A has long legs.
 
\item \verb#long_neck(A)#\idx{long\_neck/1@\verb#long_neck/1#|ee}: Animal A has a long neck.
 
\item \verb#spots(A,C)#\idx{spots/2@\verb#spots/2#|ee}: Animal A has spots of colour C.
 
\item \verb#stripes(A,C)#\idx{stripes/2@\verb#stripes/2#|ee}: Animal A has stripes of colour C.
 
\item \verb#swims(A)#\idx{swims/1@\verb#swims/1#|ee}: Animal A can swim.
 
\end{itemize}
 
Notice that I have taken care to indicate what type of thing each
argument refers to, and what the names used for individuals of each type
are. For instance I have listed the body parts used in the second
argument of \verb#has#. If you write programs for yourself, it is important to
make sure that you know what each predicate\idx{predicates!important to document|ee} does,
how many arguments\idx{arguments!must be documented|ee} it
has, what can go in or come out, and which order the arguments are in.
It is all too easy to think that you should write \verb#gives(A,milk)# when
elsewhere you have \verb#gives_milk(A)#; that you should write
\verb#colour(A,dark)# when elsewhere you have \verb#colour(A,black)#; that you
should write \verb#lays(eggs,A)# when elsewhere you have \verb#lays(A,eggs)#.
When writing down such information, you need not be as formal as
I have, but you should note it down somehow. If you have programmed
before, you will know that most computer languages let you put such
notes as comments\idx{comments|ee} in your
program. The Tutor does not allow this, but Prolog proper does, as you
will see later.
 
Care is especially necessary because Prolog does not detect spelling
errors\idx{errors!spelling|ee}. Usually they just make it say ``No''. For instance,
suppose you have the fact
\begin{verbatim}
    colour( pip, black ).
\end{verbatim}
and you ask
\begin{verbatim}
    colour( Who, dark )?
\end{verbatim}
Prolog treats \verb#dark# as completely different from \verb#black#, and will say
\verb#no#, when what you want is probably \verb#Yes - Who=pip#. The same would
happen if you were to ask
\begin{verbatim}
    colour( dark, Who )?
    black_colour( Who )?
\end{verbatim}
 
 
\subsection{Running the program}
 
Another distinction I made was between
``observable''\idx{data!observable versus non-observable|ee} and
``non-observable'' data. Given an
expert
system\idx{expert system|ee}
for diagnosing blood infections, it would be reasonable for it to ask
for the patient's age and sex, and for the location of major wounds.
It would be less reasonable for it to ask for the genus and species of the
organisms present in the blood: this can not
be observed directly, and is what the system is
supposed to be inferring. In the animal classifier, I intended the
observable data to be everything about an animal except its
classification, which
\verb#is_a#\idx{is\_a/2@\verb#is_a/2#|ee} is supposed to find for you.
So to find out what an animal is, first give it an arbitrary name, e.g.
\verb#pip#. Then add facts describing what you can observe about it:
\begin{verbatim}
    gives_milk(pip).
\end{verbatim}
and so on. Then ask
\begin{verbatim}
    is_a( pip, X )?
\end{verbatim}
 
Try this by inputting three
facts to tell Prolog that Pip is (a) feathered; (b)
black-and-white; (c) able to swim. Ask what kind of animal he is. Then
try the same for a few other animals. This resembles what you
did with the skiing advisor\idx{ski advisor|ee}.
 
 
\subsection{Names of things}
 
In Lesson 4, I said that atoms\idx{atoms!uses of|ee} can be used to name individuals, to name
classes, and to name properties. Make an alphabetical list of the atoms
in ANIMALS\idx{ANIMALS|ee} (including the name \verb#pip#), and say how each is used.
 
 
\subsection{Adding new classification rules}
 
Now have a go at extending the classifier. Start by translating the
following sentences into Prolog. If you need to talk about concepts,
such as flying ability, that the example already uses, then use the same
names. Otherwise, make up sensible names of your own, and
ensure they're consistent throughout. Note: when translating some
sentences, you may require more than one rule.
 
To illustrate something important about logic, I have chosen two
sentences that, strictly speaking, are of no help as they stand. Which
are they, and why?
 
\begin{itemize}
\item A horned ungulate is an antelope.
 
\item Bats are the only flying mammal.
 
\item Molluscs have shells.
 
\item Something with gills, fins, or scales is a fish.
 
\item Rodents have two large front teeth and side-pointing eyes.
\end{itemize}
 
Notice incidentally the different ways English has of expressing how the
properties of an object imply its classification.
 
%sann
%{\it  The two sentences are the third and fifth; in both the direction of
%implication is wrong. ``Molluscs have shells'' does not imply that all
%other animals don't have shells, so it can't be used to infer that a
%shelled animal is necessarily a mollusc. The same goes for the sentence
%about rodents. }
 
 
\subsection{Notes}
 
\idx{not/1@\verb#not/1#|(ee}
 
You will see that two of the original rules contain the test
\begin{verbatim}
    not( flies(A) )
\end{verbatim}
The \verb#not# predicate is unique amongst those you have
met so far because it
takes
a {\it goal}\idx{goals!as arguments to \verb#not/1#|ee} as argument\idx{arguments!to \verb#not/1#|ee}. Suppose you have the fact
\begin{verbatim}
    flies( pip ).
\end{verbatim}
and you ask the question
\begin{verbatim}
    not( flies(pip) )?
\end{verbatim}
You will get the answer \verb#no#. If you then delete \verb#flies(pip)# and ask
the same question, you'll get the answer \verb#yes#. So \verb#not# inverts the
truth of its argument. You can try this out on the Tutor.
 
\idx{not/1@\verb#not/1#!and variables in argument|(ee}
In some circumstances, \verb#not# can be tricky to
use. You can get an example of this by asking
\begin{verbatim}
    not( flies(P) )?
\end{verbatim}
and observing that it does not give you the names of all the non-flying
animals. More will be said about this in Lesson 6; in brief, \verb#not#
does funny things if its argument contains variables which don't have values
when \verb#not# is called. This doesn't happen in the classifier, because I've
written it so that all such variables will get values before \verb#not# is
called.
\idx{not/1@\verb#not/1#|)ee} \idx{not/1@\verb#not/1#!and variables in argument|)ee}
 
Finally, please note again that Prolog is {\it not} an expert system. \idx{expert system!Prolog as a|(ee} It
lacks features that an expert system should have,
such as an easy means of entering observable data, and an explanation in
English of its conclusions. However, for the purpose of this course,
that does not matter, and you can use Prolog to simulate the kind of
reasoning a real expert system would do.
 
\idx{expert system!Prolog as a|)ee}
 
 
\section{Prolog versus English (PP)}
 
The knowledge in an expert system can\idx{expert system|ee} be
expressed in Prolog's style of logic. But what about other kinds of
knowledge? For example, one on-going area of research is into
natural-language understanding: there are many programs that can read
text or listen to speech, and extract some kind of meaning from them. A
program called Frump was written at Yale by Roger Schank to
make summaries of news stories. It was directly connected to the
teletype output from news agencies such as Reuters and scanned the text
coming along the wire for key words and phrases, compared them with what
it knew from previous stories, and output a summary of anything new to a
printer. Such programs need some way to represent the meaning of their
input, and some form of logic is often first choice. I hope this
exercise convinces you that this is feasible.
 
    In fact, almost all schemes used for representing knowledge in A.I.,
with the possible exception of neural nets and genetic algorithms, can
be translated into the standard kind of formal logic (known as {\it
first-order predicate\idx{predicate calculus|ee} calculus}). And although Prolog is more restricted
in where it allows quantifiers\idx{quantification|ee} than formal logic, it is still possible,
by following certain rules, to translate any statement of formal logic
into Prolog.
 
    If you don't like logic, you might now be saying ``if I want to study
A.I., I should try to find a less logical language than Prolog''. That
will not help for long. Languages such as Pascal, Lisp, and Basic do at
first sight seem to require less proficiency in logic. This is because
they are lower level than Prolog, and can't accept logical statements
directly. When you're trying to represent knowledge in these languages,
you first have to decide on its logical meaning, and {\it then}
translate into a notation that's lower level and even less clear. Prolog
at least avoids some of this work.
 
    You will also find logic used as a universal language in the
A.I. literature. Many papers use it to specify what complex
programs do, or to capture patterns of human cognition. And an
increasing number of non-Prolog A.I. languages are based on logic.
That's certainly true of the languages in which most expert
systems\idx{expert system|ee} are programmed, including the eminently commercial ones used for
share dealing by big City companies. So a knowledge of logic may be
useful for your financial health \ldots
 
 
\subsection{Proverbs and other sentences}
 
\idx{proverbs|ee}
    Please start by translating the following sentences into colloquial
English. In this and future exercises, be careful with
the order of arguments in predicates. I have adopted the convention
that, where a predicate has two arguments: \verb#p(X,Y)#, then it would make
sense if written in English \verb#X p Y#.
 
    If you look at just the names, you may think you
know what the translation is going to be: several of the facts clearly
resemble familiar proverbs. However, I have deliberately mangled some of
the Prolog, so if you just rely on surface features, you may be mislead.
Also, some are not legal Prolog. Which?
 
\begin{itemize}
 
\item
\begin{alltt}
admires(P,P) :- is_a(P,narcissist).
\end{alltt}
 
\item
\begin{alltt}
hesitates(X) :- lost(X).
\end{alltt}
%sann
%{\it  This looks like ``He who hesitates is lost''. However, the
%implication is a trick: it runs in the wrong direction. }
 
\item
\begin{alltt}
colour( X, purple ) :- is_a( X, mushroom ), is_poisonous( X ).
is_poisonous( X ) :- is_a( X, mushroom ), colour( X, purple ).
colour( X, purple ), is_a( X, mushroom ).
colour( X, purple ), is_a( X, mushroom )?
\end{alltt}
 
\item
\begin{alltt}
is_good(X,architect) :- has_built(X,Y), stays_up(Y).
built_well(X,Y) :- has_built(X,Y), stays_up(Y).
\end{alltt}
 
%sann
%{\it Y is
%existentially quantified\idx{quantification!existential|ee}
%in one and universally quantified\idx{quantification!universal|ee} in
%the other.}
 
\item
\begin{alltt}
is_good(X) :-
    is_a(X,pilot),
    has_takeoffs_so_far(X,N),
    has_landings_so_far(X,N).
\end{alltt}
%sann
%{\it  Another trick. The proverb is ``A good pilot has the same number
%of take-offs as landings''. Again, the implication is, with the usual
%meaning of ``An X has property P'' the wrong way round. This can be
%demonstrated for sentence such as ``A rat has fur''
%by drawing a Venn diagram showing the set of rats inside the set of
%furry things.
%
%\begin{sloppypar}
%\idx{and@\verb#and#!errors in usage of}
%The correct proverb can't be translated in the same way, because more
%than one predicate would be needed in the head\idx{head, of fact!\verb#and# not allowed in|ee} (though a composite predicate
%\verb#has_takeoffs_and_landings_so_far# could be used).
%\end{sloppypar}
%}
 
\item
\begin{alltt}
suitable_for( X, Y ) :-
    is_a( Y, goose ), is_a( Z, goose ),
    is_male( Y ), is_female( Z ),
    suitable_for( X, Z ).
\end{alltt}
%sann
%{\it  ``X is suitable for a male goose if X is suitable for a female
%goose'', i.e. ``What's
%sauce for the goose is sauce for the gander''. }
 
\item
\begin{alltt}
better_than( X, Y ) :-
    is_act_of( X, giving ), is_act_of( Y, receiving ).
\end{alltt}
%sann
%{\it  ``It is better to give than to receive''. }
 
\item
\begin{alltt}
is_silly_fish(F) :-
    is_a(B,bait),
    was_caught_at_time_with(F,T1,B),
    was_caught_at_time_with(F,T2,B),
    T1 \B= T2.
\end{alltt}
The predicate \verb#was_caught_at_time_with(F,T,B)# means that ``F was
caught at time T using bait B''. The operator \verb#\=#\idx{\\=/2@\verb#\=/2#|ee}
means not equal, and
is here being used to compare times.
 
%sann
%{\it  ``It's a silly fish that's caught twice with the same bait.'' }
 
\end{itemize}
 
Finally: is \verb#loves(mary,everyone)# a good translation of ``Mary loves
everyone''? Is \verb#not_lonely(X) :- knows(X,someone)# a good translation of
``X is not lonely if X knows somebody''? Why or why not?
 
 
\subsection{English to Prolog}
 
    Along the same lines, have a go at translating the following
statements into Prolog. This is harder; you will need some ingenuity in
thinking up suitable predicates.
 
%sann
%{\it These are harder, but worth trying by those who know some logic.
%Some sentences, particularly ``There's no business like show-business''
%provoked heated arguments when I tried them out.}
 
\begin{itemize}
 
\item
Everything can be expressed in predicate\idx{predicate calculus!and irony|ee} calculus, even irony.
 
%sann
%{\it  \begin{sloppypar}
%Possibly
%\verb#expressible_in_predicate_calculus(X)#.
%The ``even irony'' is
%irrelevant, unless we're trying to indicate the speaker's attitude.
%\end{sloppypar}
%}
 
\item
\begin{sloppypar}
Using the predicates
\verb#unlike(Thing1,Thing2)# and \verb#is_a_business(Thing)#, translate
``There's no business like show-business''.
\end{sloppypar}
 
%sann
%{\it  This comes from an exercise in~\cite{gn}. They interpret the English as
%$\neg \exists X \mbox{is\_business}(X) \wedge \mbox{like}(X,\mbox{
%show\_business})$,
%which, negating through and using the definition of implication,
%can be rewritten as either
%$\forall X
%\mbox{is\_business}(X)
%\rightarrow
%\neg \mbox{like}(X, \mbox{show\_business})$,
%or as
%$\forall X
%\mbox{like}(X, \mbox{show\_business})
%\rightarrow
%\neg \mbox{is\_business}(X)$.
%}
 
\item There is no proverb which is not true.
 
%sann
%{\it  Possibly
%\verb#says_the_truth(X) :- is_a(X,proverb)#
%}
 
\item The Dutch proverb ``Geen koren zonder kaf'' translates as ``No corn
without chaff''. Assuming this means ``No piece of corn exists without a piece
of chaff in the same place'', translate into Prolog, using predicates
\verb#is_in(Thing,Place)# and \verb#is_a(Thing,ThingsType)#.
 
%sann
%{\it  Possibly
%\verb#is_in(Ch,P) :- is_in(Co,P), is_a(Co,corn), is_a(Ch,chaff).#
%}
\end{itemize}
 
 
\subsection{Abstract individuals}
 
\idx{abstract individuals|ee}
    You are now used to treating everyday objects like animals and
people as individuals. A.I. researchers have found, when writing natural
language processing programs, that they often need to
do the same with more
abstract things, such as acts, periods of time, and speeds. It's
interesting to see how you can do this in Prolog.
 
    For example, in Lesson 3, I justified Prolog by saying that
it makes it easy to
express sentences like ``Mary gave Fred a calculator''. You could
write this as
\begin{verbatim}
    gives( mary, fred, calculator ).
\end{verbatim}
 
But suppose we wanted to express the following:
\begin{quote}
\begin{sloppypar}
On the day before Christmas, Mary eagerly gave a diamond-studded Faberge
    calculator to Fred for his Christmas present as they languidly
    downed foaming pints of nut-brown ale, basking in the
    luxuriantly sumptuous surroundings of Oxford's Welsh Pony hotel.
\end{sloppypar}
\end{quote}
 
This sentence relates, via the act of giving, at least five pieces of
data: a time, a giver, the given, the recipient, and the place. In
addition, there are some other bits of information about the character of
the act (eager), about what else was going on at the same time, and so
on. In principle, you could write an enormous predicate with 10 or 20
arguments, allocating argument number 5
to be the place, 12 to be the character
of the act, and so on. But this would get terribly unwieldy.
 
As another example, consider expressing ``Paul gave Elspeth a book'' and
``Robb gave Carole a book''. This is no problem:
\begin{verbatim}
    gave( paul, elspeth, book ).
    gave( robb, carole, book ).
\end{verbatim}
But suppose we also want to say that Paul's gift to Elspeth was
given before Robb's gift to Carole, and we also want to indicate that
the two books were copies of the same work (but not the same
individual). It is not possible to add such information to the above
facts easily, and most A.I. programmers
would not try. Instead, they would
use a style of representation in which the acts of giving and the
books are themselves named. Here is one way to do so.
\begin{verbatim}
    act( giving, g1 ).              act( giving, g2 ).
    actor( g1, paul ).              actor( g2, robb ).
    object( g1, b1 ).               object( g2, b2 ).
    recipient( g1, elspeth ).       recipient( g2, carole ).
    is_a( b1, book ).               is_a( b2, book ).
    title(b1,'Beer Atlas of Britain').
                                    title(b2,'Beer Atlas of Britain').
    printed( b1, 1991 ).            printed( b2, 1989 ).
    edition( b1, 9 ).               edition( b2, 5 ).
    before( g2, g1 ).
\end{verbatim}
This means ``\verb#g1# is an act of giving; its actor is Paul; its object is
\verb#b1# (a book); \verb#b1# is printed in 1991'' and so on.
 
Of course, Prolog doesn't care which style you use. There are a number
of differing schemes, each with its pro- and opponents, but most
resemble in some way the one above. Such schemes usually break
down complex ideas into a large number of elementary predicates, in the
way I broke down ``Paul gave the book to Elspeth'' into the predicates
\verb#act#, \verb#actor#, \verb#object# and \verb#recipient#.
 
You will not be expected to use such schemes in the rest of this course,
although
if you want to do a project that involves generating them from
English, we have some bits of program that can help.
But it's interesting to see how they work out, and it will give you
practice in reading Prolog programs.
Below I have expressed a well-known limerick in this way. Can you work
out what it means?
\begin{verbatim}
    is_a(l1,lady).
    has_age(l1,young).
    started_during(t,d1).
    slower( c, s ).
    follows(d1,d2).
    is_a( s, speed ).
    follows( n, d2 ).
    took_trip(l1,t).
    velocity_of( light, c ).
    is_a(d2,day).
    is_a( c, speed ).
    velocity_of( l1, s ).
    is_a(d1,day).
    is_a(n,night).
    ended_during(t,d2).
    is_a( t, trip ).
\end{verbatim}
 
%sann
%%{\it
%%\begin{verse}
%%There was a young lady named Bright\\
%%whose speed was far faster than light\\
%%    She went out one day\\
%%    In a relative way\\
%%And returned on the previous night.
%%\end{verse}
%%I have set others for translation, but for the sake of decency,
%%omit them here, referring the interested reader to~\cite{baring gould}
%%and~\cite{parrott}. One can introduce semantic nets
%%by a similar exercise, drawing diagrams of some
%%sample translations and asking the
%%students to perform others of their own. For cognitive scientists, the
%%abstract individuals exercise above could be linked with Chapter
%%5 of~\cite{scott}, which explains in some detail how conceptual dependency can
%%be represented in Prolog, and which describes a simple script-applying
%%program based on it.}
 
 
\section{Navigating through data structures (PE,AI)}
 
\idx{navigating round data structures|(ee}
 
Generally, Prolog programs often fall into two parts. One is fixed
data --- networks, family trees, and so on ---
described
by structural\idx{structural predicates|ee} predicates like
\verb#meets#\idx{meets/2@\verb#meets/2#|ee}
and \verb#is_a#;
the other is some component which
wanders around it, changing facts, generating output,
reading input, and so on. You have already had some practice at
expressing the fixed data, and
in Lessons 7 and 8, you will get an idea
of how to do the navigation\idx{predicates!command|ee}. To prepare you for this, some
examples of what you can do by
navigating are shown in the rest of this supplement.
While reading them, you may like to bear in
mind the following quote:
\idx{Winter Aid fund|ee}
\begin{quotation}
        A German with starving wife and family sought assistance from
    the Winter Aid Fund. Entering an imposing building, he found himself
    facing two doors, one marked ``Party Members'', the other
    ``Non-Party Members''. Going through the second door he was faced
    with two more, one marked ``Subscribers to the Fund'', and the other
    ``Non-Subscribers to the Fund''. Going through the latter, he was
    once again faced with two more doors, and so on. After an hour or
    two, having come to two doors, one marked ``Single Men'', the other
    marked ``Family Men'', he chose the latter and found himself out in
    the street where he had started. A friend asked him whether he had
    got any help. ``No'' he said, ``but heavens, what organisation!''.
\end{quotation}
 
%sann
%{\it Quoted in ``Towards Information Retrieval'' \cite{fa:ir}.}
 
 
\subsection{Science fiction stories}
 
\idx{science fiction generator|(ee}
 
Start by restoring
knowledge base \verb#spin#\idx{SPIN|ee} with the command \verb#restore spin#.
It defines a predicate with no arguments at all, also called \verb#spin#\idx{spin/0@\verb#spin/0#|ee}.
Since all
the predicates you have seen so far have had arguments, you may find it
hard to see how argument-less predicates\idx{predicates!nullary|ee} could be any use.
After all, the truth value of a predicate depends on its arguments;
surely, if it has none, then it must be always true or always false?
However, as we shall
see in Lesson 7, such predicates can be useful. There
is more to Prolog than logic.
 
    Start by calling \verb#spin# a few times, by asking the question
\begin{verbatim}
    spin?
\end{verbatim}
 
    Now, have a look at the knowledge base. It contains a number of
unconditional facts whose predicate is \verb#element#\idx{element/3@\verb#element/3#|ee}, with three arguments.
How do they describe the stories \verb#spin# generates? Sketch the process by
which you think \verb#spin# operates.
 
Note incidentally that the arguments to
\verb#element# are almost all quoted\idx{quotes|ee} atoms\idx{atoms!syntax of|ee}. We need to quote them because
they contain spaces, capitals and other funny characters that would not
make sense in unquoted atoms.
 
%sann
%{\it \verb#spin# operates on facts which describe nodes in a
%directed graph, each
%node labelled with some science-fictional phrase. It finds a random path
%through the graph, and writes out the labels in order, thereby
%generating a short science-fiction story. I based the idea on~\cite{sf},
%but with many additions.
%}
 
\idx{science fiction generator|)ee}
 
 
\subsection{Musical rhythms}
 
\idx{fugue generator|(ee}
\idx{music generator|(ee}
\idx{rhythm generator|(ee}
 
    Now restore \verb#notes#\idx{NOTES|ee}. Call \verb#spin#\idx{spin/0@\verb#spin/0#|ee} again. Now it generates
rhythms to be used as a basis for fugues. In the output, \verb#c# means crotchet;
\verb#m# minim, and \verb#q# quaver. This is taken from a
previous practical project, namely a fugue-generating
program written by Lucy Mackintosh, which first generated a basic
two-bar rhythm
structure, then superimposed a melody, and finally constructed other
harmonically-related melodies for the other voices. The melody generator is
rather too complicated for this stage of the course, so what I've shown
you is just the rhythm part.
 
\idx{fugue generator|)ee}
\idx{rhythm generator|)ee}
\idx{music generator|)ee}
 
 
\subsection{Prolog and grammars}
 
\idx{grammars|(ee}.
 
By altering the clauses for \verb#element#\idx{element/3@\verb#element/3#|ee}, you
can describe a variety of other
structures, for example menus, conversations, or stages in someone's
lifetime: school leads to PPE or psychology or philosophy; PPE leads to
merchant banking; psychology leads to a D.Phil and thence to academic
fame; philosophy leads to destitution \ldots. You might try this. When
you have done so, you can call \verb#spin#\idx{spin/0@\verb#spin/0#|ee} again.
 
This is a very simple demonstration of Prolog in
grammar-writing:
we are all familiar with grammars for describing sentences, but they can
also describe other structures, such as stories or music.
In general, you can use a grammar in one of two ways.
The first is for analysing structures into
their parts. The second, which we do here,
is generating structures from those parts.
 
These kinds of grammar, incidentally, have been made out of some very simple Prolog
components, and would not really be suitable for describing the
structure of sentences. (Why?) However,
Prolog also contains a special
feature called DCG rules\idx{DCG rules|ee} that
allow you to write grammars for natural languages very easily.
If you want to try your hand at this, ask later on
in the course.
 
Note that the grammar in SPIN\idx{SPIN|ee}
lacks coherence between its elements,  as was  probably
obvious from some of the stories. In the same way, a grammar for English
which stated that
\begin{verbatim}
    A sentence is a noun phrase followed by a verb phrase
\end{verbatim}
would not as it stands prohibit singular nouns from being followed by
plural verbs. Nor would it prohibit sentences like ``Melancholy Justice
flirted purposefully with 127 purple elephants''. To take account of
such things, we need some way to specify {\it
agreement}: to say that the form of one element much
depend on that of another. You can do this easily with DCG rules.
 
%sann
%%{\it Chapter 4 of~\cite{scott} contains some natural-language parsing
%%projects using DCGs}.
 
\idx{transition matrix|(ee}
 
Incidentally, SPIN\idx{SPIN|ee}
is similar to a {\it transition matrix}
which is
another method used to describe behaviour and changes of state in a
system. In a transition matrix, each element of the grammar is linked
to each element which can follow it by a number: the number specifies
the probability that one will succeed the other. So instead of, as in
\verb#spin#, choosing any branch with equal probability, we can state that
some branches are high-probability and others are very low. Here's one
way we might encode a transition matrix for behaviour at CTC:
\begin{alltt}
    state( 1, do_next_exercise ).\idx{state/2@\verb#state/2#|ee}
    state( 2, go_and_drink_coffee ).
    state( 3, leave_in_disgust ).
    state( 4, leave_happy ).
    state( 5, ask_for_help ).
    state( 6, apply_help_given ).
 
    prob( 1, 1, 0.2 ).  prob( 1, 2, 0.2 ).  prob( 1, 3, 0.5 ).\idx{prob/3@\verb#prob/3#|ee}
    prob( 1, 4, 0.05 ). prob( 1, 5, 0.05 ). prob( 1, 6, 0 ).
\end{alltt}
Here, \verb#prob(X,Y,P)#  means ``there is a  probability of P  that state Y
will follow state X''. There is no chance of state 6 following state 1;
it  can only follow  state 5 (you can't apply help you
don't have). We could write a modified \verb#spin# that took these
probabilities into account, and you might find the idea useful if you
want to have a go at story generation or something similar.
 
\idx{transition matrix|)ee}
\idx{grammars|)ee}.
 
 
\subsection{Diagnosis}
 
\idx{depression diagnoser|(ee}
 
    Now restore DEPRESSION\idx{DEPRESSION|ee}. This knowledge base defines a no-argument
predicate called \verb#run#,\idx{run/0@\verb#run/0#|ee} for
diagnosing the causes of depression in
terms of provoking agents and
vulnerability factors. Like the
fugue-generator, it was written as a previous practical project, this
time by Alison Fry.
 
    To use the program, type \verb#run?#.
It will pose you a number of questions about your current and
past circumstances: to answer them,
type \verb#y# or \verb#n# (or, if requested, a number),
followed by a RETURN. You do not need a full
stop after the reply.
When answering, the worse you make things seem, the more factors that will
appear in the diagnosis.
 
    Look at the knowledge base again. What structure do the facts
define, and how do you think they're used?
 
%sann
%{\it The theory of depression embodied here is taken from~\cite{bh}.}
 
\idx{depression diagnoser|)ee}
 
 
\subsection{Note}
 
You have now encountered two kinds of diagnostic system.
The first, the animal classifier\idx{animal classifier|ee}, was written by converting each rule
directly into a Prolog clause, then relying on Prolog's
question-answering ability to get results.
 
The second, the
depression system\idx{depression diagnoser}, worked at a different level. Instead of translating
each rule directly to Prolog, I followed the Winter Aid Fund quote, and
built a kind of network. Think in terms of rooms, where each
room contains a question. You take a different
exit for each possible answer to this question,
thus coming to a new room in which there
sits either another question or a diagnosis. You may find this way of
doing things useful for your project: many students do.
 
%sann
%{\it If students look as though they are having trouble with Prolog
%control, I suggest that they work on such a
%``navigation'' project,
%concentrating on the logical structure of the data, and leaving me to
%provide a ready-made control component. This is how
%the depression diagnoser\idx{depression diagnoser}
%was written.}
 
\idx{navigating round data structures|)ee}
 
 
\section{The game of Traveller (PP)}
\label{ch:lesson4:traveller}
 
 
\subsection{The board}
 
\idx{Traveller!introduction to|(ee}
 
    In the previous section, you saw that Prolog can be used to navigate
around structures defined by sets of facts. The following program
navigates in a more literal sense. Please start by looking at the file
entititled BOARD\idx{BOARD|ee} which comes with this supplement. It defines the basic
predicates \verb#square#, \verb#building#, \verb#joins#, \verb#in#, \verb#loop#, \verb#sells_fuel#,
\verb#buys# and \verb#sells#, plus three ones derived from them: \verb#adjacent#,
\verb#clockwise# and \verb#distance#.
 
Together, these describe a simple street layout, with squares containing
shops and fuel stations. Unlike Monopoly\idx{Monopoly|ee},
the squares are not confined
to the outside of the board, but can form streets, some
looped\idx{loop roads!in Traveller|ee}
back on
themselves, wandering over its interior.
 
%sann
%{\it  A diagram of the board appears
%in Figure~\ref{ch:lesson4:board}. This should be handed out with
%Supplement 4. Since there is as yet no
%standard for transferring graphics, I cannot include a machine-readable
%copy on the source disc.
%\begin{figure}
%\vspace{\textheight}
%\caption{The board for Traveller}
%\label{ch:lesson4:board}
%\end{figure}
%
%\idx{Traveller!creating new boards|(}
%To avoid having to input all the co-ordinates and square numbers, I
%have a shorthand language for describing the board: BOARD.DAT\idx{BOARD.DAT} contains
%the current game in this form. BOARDGEN.PL\idx{BOARDGEN} preprocesses it
%into Prolog and allocates square numbers: comments in the program
%explain the syntax used in BOARD.DAT.\idx{BOARD.DAT}\@ The output from this is in
%BOARD.PL.
%
%In this supplement, I assume that BOARD is a printed copy which you will
%make of BOARD.PL, together with the definitions for
%\verb#adjacent#\idx{adjacent/2@\verb#adjacent/2#!creating Traveller boards},
%\verb#clockwise#\idx{clockwise/2@\verb#clockwise/2#!creating Traveller boards}
%and \verb#distance#\idx{distance/3@\verb#distance/3#!creating Traveller boards} from
%TRAVELLER.PL\idx{TRAVELLER}. This latter is the source of
%Traveller, and consults BOARD.PL.
%
%All squares on the board lie
%on integer co-ordinates, and are connected if at all by
%vertical, horizontal, or 45-degree lines. Given BOARD.PL and a decent
%graphics interface, it should be easy to
%generate a diagram, either by
%calling plotting routines, or by emitting the
%diagram directly as PostScript or some other graphics\idx{graphics!Traveller in}
%\idx{Traveller!displaying graphically} driver language.
%Expert Systems Ltd.\ ``Prolog-2 with Windows'' implements predicates
%that call the Microsoft Windows routines, and I have a version of
%Traveller for this system that draws a game board on the screen,
%representing traders by moving van-shaped icons and their state by
%dialog boxes which are updated as the game runs.
%
%The disc contains, in BOARDTEX.PL, a program that generates
%\LaTeX\ picture environment commands ---
%these plot the squares, numbers, and shop names, but not
%the connecting roads. Because of their length, it
%is difficult to position the shops'
%names automatically, so the diagram in this book was redrawn by hand
%(with thanks to Mark Lewis) from the automatically generated version.
%\idx{Traveller!creating new boards|)}
%
%Section~\ref{ch:lesson4:gamedesign} discusses the
%design of Traveller.}
%
    More specifically, the predicates have the meanings given
below:
\begin{itemize}
 
\item \verb#square(S,X,Y)#\idx{square/3@\verb#square/3#|(ee}:
S is the number of a square, lying at co-ordinate
$(X,Y)$. Each square has a unique number; these are integers (whole
numbers), and work upwards from 1. Adjacent squares do not necessarily
have adjacent numbers.
\idx{square/3@\verb#square/3#|)ee}
 
\item \verb#building(S,B)#\idx{building/2@\verb#building/2#|(ee}:
B is the name of the building in square number S.
\idx{building/2@\verb#building/2#|)ee}
 
\item \verb#joins(S1,S2)#\idx{joins/2@\verb#joins/2# (Traveller)|ee}: whereas \verb#square#
defines where squares lie and what they
contain, \verb#joins# defines how they are connected. There is one clause,
\verb#joins(S1,S2)# for every pair of connected squares. To make things
simple, squares can only be connected by vertical, horizontal, or
45-degree diagonal lines.
\idx{joins/2@\verb#joins/2# (Traveller)|ee}
 
\item \verb#in(S,L)#\idx{in/2@\verb#in/2#|(ee}: \idx{loop roads!in Traveller|ee}
The board contains several streets that curve back on
themselves, forming closed loops.
Each loop has a name (you will see why
later). There is one clause, \verb#in(S,L)# for every square S that lies in a
loop called L. You can think of the loops as being distinct regions of a
city, such as the City in London or the central part of Oxford, except
that to keep things simple, they do not contain any roads apart from the
loop itself.
\idx{in/2@\verb#in/2#|)ee}
 
\item \verb#loop(L)#\idx{loop/1@\verb#loop/1#|(ee}:
This defines the names of the loops. There is one
clause for each loop.
\idx{loop/1@\verb#loop/1#|)ee} \idx{loop roads!in Traveller|ee}
 
\item \verb#adjacent(S1,S2)#\idx{adjacent/2@\verb#adjacent/2#|(ee}:
This is true if S1 joins S2. Note that it is
defined in terms of \verb#joins#\idx{joins/2@\verb#joins/2# (Traveller)|ee}:
S1 is next to S2 if S1 joins S2 or S2 joins
S1. The reason for this is something we alluded to in the cave world\idx{caves world|ee}
example of Supplement 2. If Prolog has a fact such as
\begin{verbatim}
    joins(66,67).
\end{verbatim}
it does not automatically assume that the converse --- \verb#joins(67,66)#
--- is true. So we have to define a new predicate
which holds no matter
which way the squares are said to be joined. We could instead have had
two sets of facts --- both \verb#joins(66,67)# and \verb#joins(67,66)# --- but
this would waste space.
 
The import of this is that if you want to find out about connected
squares, you should use \verb#adjacent#, not \verb#joins#.
\idx{joins/2@\verb#joins/2# (Traveller)|ee}
\idx{adjacent/2@\verb#adjacent/2#|)ee}
 
\item \verb#clockwise(S1,S2)#\idx{clockwise/2@\verb#clockwise/2#|(ee}:
This is true if square S1 and S2 are both in
the same loop\idx{loop roads!in Traveller|ee},
and S2 is immediately next to, and clockwise of, S1. Its
purpose is to give you a simple way of finding your way round loops. It
is defined in terms of \verb#joins#\idx{joins/2@\verb#joins/2# (Traveller)|ee},
and only works because I took care, when
generating the board definition, to make sure that the
\verb#joins#\idx{joins/2@\verb#joins/2# (Traveller)|ee} facts
always had their arguments in an order which would make it work.
\idx{clockwise/2@\verb#clockwise/2#|)ee} \idx{loop roads!in Traveller|ee}
 
\item \verb#distance(S1,S2,D)#\idx{distance/3@\verb#distance/3#|(ee}:
This sets D to the distance between S1 and
S2. It uses \verb#is#\idx{is/2@\verb#is/2#|ee}, an operator for doing arithmetic\idx{arithmetic!and \verb#distance/3#|ee} that you'll meet in
Lesson 6. The formula is the standard one for working out distance in
terms of X
and Y co-ordinates: \verb#X^2# means X squared, and \verb#sqrt(...)# means the
square root of.
\idx{distance/3@\verb#distance/3#|)ee}
 
\end{itemize}
 
If you care to compare the BOARD\idx{BOARD|ee} file with the diagram of the board, it
should become clear what these facts say.
 
 
\subsection{The buildings}
 
In this era of recession --- I wrote that nine months ago, and it is still true! ---  it is important that we all be good
consumers and keep the economy moving. The macro-economic knowledge
base of Supplement 2 showed what happens when we fail. So, bearing this
in mind, the buildings all concern buying and selling, as you may have
guessed from their names.
 
There are three kinds of building: wholesalers, retailers, and
fuel-stations. Each retailer sells one (and one only) of five types of
good to the public: coal, diamonds, glasses (tableware, not eyewear),
peaches, and televisions. The retailers buy their stocks from traders,
who in turn buy from wholesalers. By buying cheap at a wholesaler and
selling dear to a retailer, a smart trader can make a hefty profit.
Wholesalers, retailers, and fuel-stations are described by the facts
below:
 
\begin{itemize}
 
\item \verb#sells(B,Good,Price)#\idx{sells/3@\verb#sells/3#|(ee}: B names a wholesaler, and will be
one of the names given as the first argument of \verb#building#\idx{building/2@\verb#building/2#|ee}. Good is the
type of product sold. Like retailers, each wholesaler deals
in only one kind of product. Price is the price at which the wholesaler
sells one unit of the product to a trader (i.e. the price at which the
trader {\it buys} it).
\idx{sells/3@\verb#sells/3#|)ee}
 
\item \verb#buys(B,Good,Price)#\idx{buys/3@\verb#buys/3#|(ee}:
B names a retailer. As before, Good
is the product type. This time, Price is the price at which
the retailer buys from the trader, i.e. the price at which the trader
{\it sells} it.
\idx{buys/3@\verb#buys/3#|)ee}
 
\item \verb#sells_fuel(B,Price)#\idx{sells\_fuel/2@\verb#sells_fuel/2#|(ee}:
This tells you which buildings are fuel
stations. Price is the price per unit of fuel, and B is the name of the
building.
\idx{sells\_fuel/2@\verb#sells_fuel/2#|)ee}
 
\end{itemize}
 
\idx{Traveller!introduction to|)ee}
 
 
\subsection{Trading}
 
\idx{Traveller!how to write a trader|(ee}
 
To play Traveller, you have to move around the board, making as much
profit as possible. It takes some skill to keep going: for example, you
must not allow yourself to run out of fuel. But there is a twist. You
yourself are not playing Traveller --- or not directly. It is your task
to program an automatic trader in Prolog, and to give it rules that
determine when and where to buy, sell, or move. Once you start your
trader off, it must run without any help from you. The only thing you
can do is to watch the output: sympathise if it runs out of fuel or
money; applaud if it makes a huge profit.
 
Before showing you how to program a trader, I need to say some more
about prices. Goods are bought and sold in ``units''. So a trader may
tell Prolog that it wants to buy 20 units of coal, or to sell 100 units
of diamonds. To make Traveller more realistic, you can think of these
units as being sacks (of coal); individual boxes (for diamonds and
televisions); boxes of six (glasses); boxes of twenty-four (peaches).
However, it doesn't matter how many things are inside; you can only buy
in whole units.
 
The buying and selling prices given by \verb#buys#\idx{buys/3@\verb#buys/3#|ee} and \verb#sells#\idx{sells/3@\verb#sells/3#|ee} are all quoted
as the price per unit.
 
Products have volumes, measured in cubic feet. These are given by the
only fact I haven't yet mentioned:
\verb#unit_volume(Good,V)#\idx{unit\_volume/2@\verb#unit_volume/2#|(ee}.
V is the
volume occupied by one unit of Good (all goods of the same type have
the same unit volume --- containerisation). This matters because as a
trader, you drive a lorry whose size is strictly limited. It has a
capacity of 1000 cubic feet. You can always fill it up to this amount,
provided you have the money, but you cannot cram in any more above the limit.
\idx{unit\_volume/2@\verb#unit_volume/2#|)ee}
 
When you start off, you are given \pounds 5000 in cash, to spend as you
will. There is no upper limit on your cash --- you can accumulate
indefinitely --- but you are not allowed to go below zero. There are no
credit facilities in this game.
 
Your lorry has a fuel tank whose capacity is twenty units. When you
start off, it is full. At each stage in the game, you are allowed to do
one of four things:
\begin{itemize}
 
\item Buy some fuel.
 
\item Buy some stock from a wholesaler.
 
\item Sell some of your stock to a retailer.
 
\item Move one unit along any road.
 
\end{itemize}
Thus, when you move, you can only move to an adjacent square, and then
only if it is connected to your current square. Each move costs one unit
of fuel, so after twenty moves you will be out of the game unless you
remember to refuel.
 
To buy or sell, you must be on the same square as the person you're
dealing with. You can only buy (fuel or tradeable goods) if you have
enough money; otherwise you will be thrown out of the game for fraud. If
you try to buy more fuel than you have room for in your tank, you will
certainly spend the money; your tank will be filled, and any excess will
just be spilt. However, if you try to buy more of a good than you have
room for, the transaction will be forbidden for safety reasons, and you
will be kicked out as an unsafe driver.
 
You can only sell a good if you have enough of it in your lorry. If you
haven't, you will again be thrown out for fraud.
 
 
\subsection{Running a trader}
 
Now, please do the following. Start up your Tutor, and switch into
Prolog mode. Then do
\begin{alltt}
    load traveller.\idx{TRAVELLER|ee}
\end{alltt}
This will load the software which implements the game. As with some
earlier examples, you must \verb#load#\idx{load@\verb#load# command!in Traveller|ee}
and not \verb#restore# this file, though
for a different reason:
it contains a lot of code, and restoring it would clog
the editor. Having loaded it, the predicates it defines will be in the
database\idx{database!in Traveller|ee}, but not in the textbase\idx{textbase!in Traveller|ee},
so you won't be able to examine them.
However, if you're interested, your teacher can show you a listing of
the file. Now do
\begin{verbatim}
    load trader.
\end{verbatim}
This loads code which defines a particular kind of trader. Finally, type
the question\idx{run/2@\verb#run/2#|ee}:
\begin{verbatim}
    run( trader, 67 )?
\end{verbatim}
 
The game will start by giving the display below. The fuel and tank size
are written out in
units; each trader begins with a full tank. Initial cash is
\pounds 5000, and initial loads are all zero. The total load is
displayed in
cubic feet, and the stock of each good is displayed both in units and in
cubic feet, using \verb#unit_volume#\idx{unit\_volume/2@\verb#unit_volume/2#|ee} to provide conversion factors.
\begin{verbatim}
trader is on square 67.
  Fuel 20 in tank size 20.
  Cash 5000.
  Total load 0 cu ft in lorry size 1000.
    Stock of televisions = 0 units (0 cu ft).
    Stock of peaches = 0 units (0 cu ft).
    Stock of glasses = 0 units (0 cu ft).
    Stock of diamonds = 0 units (0.0 cu ft).
    Stock of coal = 0 units (0 cu ft).
\end{verbatim}
 
As the game continues, you will see a summary of the actions the trader
takes at each turn, and the result on his fuel, cash, position, and
stocks. Wait until the trader makes his way to The Hub, and has gone
through a few cycles of buying and selling; when you have
seen enough, you
can interrupt\idx{interrupts!in Traveller}
the game. Incidentally, the game is not particularly fast;
you will see why below.
 
%sann
%{\it  In the Poplog implementation of the Tutor, it is possible
%to trap the
%student's interrupts\idx{interrupts!trapping}
%and abort whatever goal\idx{questions!interrupting} is
%running and then call the read-execute loop. I assume that you can
%implement something similar, to enable
%students to abort running programs.
%
%I have also assumed that your terminals provide some way of suspending
%and resuming output, as is done by CONTROL-S and CONTROL-Q on the
%VAX. If not, it will be necessary to implement some means of pausing,
%perhaps by displaying only a page at a time. On a system with
%windowing, the display can be made much more attractive, depicting the
%progress of the trader around a diagram of the board, with a small
%constantly-updated inset showing his current state. }
 
Now, how can you write a trader of your own? Well, when
you call \verb#run#\idx{run/2@\verb#run/2#|ee}, it
starts by asserting some clauses which describe the trader's
state. These are:
 
\begin{itemize}
 
\item \verb#at(T,Square)#\idx{at/2@\verb#at/2#|(ee}:
T is the name of the trader, and Square is the
number of the square he is on. This always starts off as the second
argument to \verb#run#\idx{run/2@\verb#run/2#|ee}.
\idx{at/2@\verb#at/2#|)ee}
 
\item \verb#carries(T,Good,Qty)#\idx{carries/3@\verb#carries/3#|(ee}:
T is the name of the trader, Good is the name
of one of his goods (\verb#coal#, \verb#diamonds#, \verb#glasses#, \verb#peaches# or
\verb#televisions#)
and Qty is the number of units he has. This predicate was
originally called \verb#load#, but I have changed it to avoid clashes with the
\verb#load# command.
\idx{carries/3@\verb#carries/3#|)ee}
 
\item \verb#cash(T,Cash)#\idx{cash/2@\verb#cash/2#|(ee}:
T is the name of the trader, and Cash is the
amount of cash he has.
\idx{cash/2@\verb#cash/2#|)ee}
 
\item \verb#fuel(T,Qty)#\idx{fuel/2@\verb#fuel/2#|(ee}:
T is the name of the trader, and Qty is the number
of units of fuel he has.
\idx{fuel/2@\verb#fuel/2#|)ee}
 
\item \verb#max_load(T,Vol)#\idx{max\_load/2@\verb#max_load/2#|(ee}:
T is the name of the trader, and Vol is the
maximum volume his lorry can hold. In this version of Traveller, it is
1000 cubic feet.
\idx{max\_load/2@\verb#max_load/2#|)ee}
 
\item \verb#tank_size(T,Qty)#\idx{tank\_size/2@\verb#tank_size/2#|(ee}:
T is the name of the trader, and Qty is
the maximum number of units he can get into his tank. In this version of
Traveller, it's 20.
\idx{tank\_size/2@\verb#tank_size/2#|)ee}
 
\item \verb#total_load(T,Vol)#\idx{total\_load/2@\verb#total_load/2#|(ee}:
T is the name of the trader, and Vol is
the total load in cubic feet.
\idx{total\_load/2@\verb#total_load/2#|)ee}
 
\end{itemize}
 
The name T of the trader is the first argument to
\verb#run#\idx{run/2@\verb#run/2#|ee}. So for \verb#run(trader,67)#, you get clauses
\begin{verbatim}
    at(trader,67).
    cash(trader,5000).
    fuel(trader,20).
    carries(trader,coal,0).
    carries(trader,diamonds,0).
    carries(trader,glasses,0).
    carries(trader,peaches,0).
    carries(trader,televisions,0).
    max_load(trader,1000).
    tank_size(trader,20).
    total_load(trader,0).
\end{verbatim}
Note that, apart from \verb#carries#, there is only one clause of each kind.
 
Having done this, \verb#run#\idx{run/2@\verb#run/2#!how it works|ee}
then tries to find out what the trader's first action is to be. Will he
move to a new square, buy something, or sell something? It
does so by calling (i.e. by asking itself the question)
\begin{alltt}
    act( T, Action, Arg1, Arg2 )\idx{act/4@\verb#act/4#|(ee}
\end{alltt}
where T is the name of the trader. The file TRADER\idx{TRADER|ee} contained clauses
{\it I}
have written for \verb#act#: to play Traveller, {\it you} must write some for
your trader.
 
When \verb#act# is called,
it must set Action to one of \verb#move#, \verb#buy#, or \verb#sell#. If Action is
\verb#move#, Arg1 must become the next square to move to, and Arg2 must
become the atom \verb#dummy#. If Action is \verb#buy# or \verb#sell#, Arg1 must become
the name of a good, and Arg2 must become the quantity in units that is
to be bought or sold. Finally, if Action is \verb#buy#, Arg1 can also be
\verb#fuel#. In this case, the trader is buying fuel, not a good for resale.
 
 
\subsection{What facts does {\tt act} need?}
 
\idx{act/4@\verb#act/4#!how to write|(ee}
 
You can demonstrate this in the following way. Do
\begin{alltt}
    restore circler.\idx{CIRCLER|ee}
\end{alltt}
This loads a simple version of \verb#act#, driving a trader named \verb#circler#.
Since it's a \verb#restore#, the predicate is visible in the textbase\idx{textbase!in Traveller|ee},
so you
can look at its definition. There is one clause, which makes the circler
always move clockwise, never buying nor selling. Try
\begin{verbatim}
    run( circler, 18 )?
\end{verbatim}
and see what happens.
 
Now, how can you try \verb#act# for yourself? You need several things.
Firstly, the board-description predicates \verb#square#\idx{square/3@\verb#square/3#|ee}, \verb#building#\idx{building/2@\verb#building/2#|ee}, \verb#in#\idx{in/2@\verb#in/2#|ee},
\verb#loop#\idx{loop/1@\verb#loop/1#|ee},
\verb#adjacent#\idx{adjacent/2@\verb#adjacent/2#|ee},
\verb#clockwise#\idx{clockwise/2@\verb#clockwise/2#|ee},
\verb#distance#\idx{distance/3@\verb#distance/3#|ee},
\verb#sells#\idx{sells/3@\verb#sells/3#|ee},
\verb#buys#\idx{buys/3@\verb#buys/3#|ee} and \verb#sells_fuel#\idx{sells\_fuel/2@\verb#sells_fuel/2#|ee}
must be in place. Well, this would have happened when you loaded
TRAVELLER\idx{TRAVELLER|ee}. The predicates are not in the
textbase\idx{textbase!in Traveller|ee},
so you can't change
them; but they are in the database\idx{database!in Traveller|ee},
so you can ask questions concerning
them. If you're not convinced, try a few questions, for example
\begin{verbatim}
    adjacent( 66, Where )?
    clockwise( 18, Where )?
    in( 18, Region )?
    in( Which, 'The Hub' )?
    distance( 18, 20, D )?
    sells( B, Good, Qty )?
\end{verbatim}
Satisfy yourself that these predicates do exist, and that you know exactly
what they are for.
 
Secondly, you need to fake up some facts which represent a \verb#circler# at
some point in its travel. These are the ones defined by \verb#at#\idx{at/2@\verb#at/2#|ee},
\verb#carries#\idx{carries/3@\verb#carries/3#|ee}, \verb#cash#\idx{cash/2@\verb#cash/2#|ee},
\verb#fuel#\idx{fuel/2@\verb#fuel/2#|ee}, \verb#max_load#\idx{max\_load/2@\verb#max_load/2#|ee}, \verb#tank_size#\idx{tank\_size/2@\verb#tank_size/2#|ee} and \verb#total_load#\idx{total\_load/2@\verb#total_load/2#|ee}. These are
treated specially. As \verb#run#\idx{run/2@\verb#run/2#|ee} proceeds, it updates not only the database\idx{database!in Traveller|ee}
but also the textbase\idx{textbase!in Traveller|ee} with these predicates. This means that if you
interrupt\idx{interrupts!in Traveller}
a \verb#run#, and do a \verb#show#\idx{show@\verb#show# command!with negative fact numbers|ee}, you should see their clauses.
Incidentally, some of them will have negative numbers, because they get
added before any other fact\idx{fact numbers!negative|ee}. This is quite OK, as you'll see in Lesson
7. You can edit these facts as for any others, e.g.
\verb#delete -10#\idx{delete@\verb#delete# command!with negative fact numbers|ee},
\verb#show -200/300#.
Note also that, very occasionally, one
of the clauses might be missing. This will happen if you caught \verb#run#
just between deleting one clause and replacing it by its successor. The
chance of this is small; about the same as catching the A.C. mains
supply precisely at zero if you stick your fingers into a wall socket.
 
Convince yourself that these predicates do exist, and are editable, by
starting a \verb#run#, interrupting\idx{interrupts!in Traveller}
it and doing a \verb#show#.
 
 
\subsection{Continuing a run}
 
Now, one way to get familiar with these predicates is to change
one of them and then re-start a run. As well as \verb#run#, TRAVELLER\idx{TRAVELLER|ee}
defines the predicate \verb#go_on#\idx{go\_on/1@\verb#go_on/1#|ee}. This takes one argument, the name of a
trader, and continues from where it left off. Before starting, \verb#go_on#
checks that all the facts it needs are there; if not, it warns you and
stops.
 
You can demonstrate this by starting another run. So type
\begin{verbatim}
    run( circler, 18 )?
\end{verbatim}
 
After about five moves, interrupt\idx{interrupts!in Traveller}
it and do a \verb#show#. Check that each of
the predicates needed is there. Then type
\begin{verbatim}
    go_on( circler )?
\end{verbatim}
This will continue the circler from where he left off.
 
After some time, the circler will run out of fuel. You can give him some
more by changing the clause for \verb#fuel#\idx{fuel/2@\verb#fuel/2#|ee}, and then doing another \verb#go_on#\idx{go\_on/1@\verb#go_on/1#|ee}.
Try it.
 
 
\subsection{Testing {\tt act}}
 
You are now ready to try out \verb#act#. Look at the definition of \verb#act#
restored from CIRCLER\idx{CIRCLER|ee}. The only trader-state predicate it calls is \verb#at#\idx{at/2@\verb#at/2#|ee}.
This means that, so long as you have a clause for \verb#at#, you can test
this version of \verb#act#. So input one --- \verb#at(circler,18)#, perhaps --- and then
type
\begin{verbatim}
    act( circler, Action, Arg1, Arg2 )?
\end{verbatim}
You should find that Action becomes \verb#move#, Arg1 is whichever square is
clockwise of the current one, and Arg2 is \verb#dummy#.
 
All this may have seemed rather long-winded, but the gist of it can be
stated quickly. To run a trader, you call \verb#run#\idx{run/2@\verb#run/2#|ee}, passing it the trader's
name and initial square. To find out what the trader will do next, \verb#run#
calls \verb#act#, passing the trader's name in the first argument, and
getting back the name of an action, plus some other information in the
other arguments. \verb#act# has two sources of information. The first is the
board predicates. These are \verb#load#ed\idx{load@\verb#load# command|ee}, so they appear in the database\idx{database!in Traveller|ee},
but you can't edit them. The second is the predicates that describe a
trader's current state. All these take the trader's name as their first
argument. As \verb#run# proceeds, it updates these in the database\idx{database!in Traveller|ee} and also
in the textbase\idx{textbase!in Traveller|ee},
so you can see and change them. If you want to continue
a run from where it left off, perhaps after changing some of the state
predicates, you can use \verb#go_on#\idx{go\_on/1@\verb#go_on/1#|ee}. This takes one argument, the trader's
name. Finally, you can of course ask questions that involve \verb#act#
directly, if you want to test how it responds to various situations.
 
\idx{act/4@\verb#act/4#!how to write|)ee}
\idx{act/4@\verb#act/4#|)ee}
 
 
\subsection{A bit of practice}
 
Can you now define the following predicates:
 
\begin{itemize}
 
\item \verb#square_sells( Square, Good, Price )#\idx{square\_sells/3@\verb#square_sells/3#|ee}: This holds if Square sells
Good at Price.
 
\item \verb#square_buys( Square, Good, Price )#\idx{square\_buys/3@\verb#square_buys/3#|ee}: This holds if Square buys
Good at price.
 
\item \verb#at_seller( T, Good, Price )#\idx{at\_seller/3@\verb#at_seller/3#|ee}: This is true if trader T is at a
square which sells Good at Price.
 
\item \verb#at_buyer( T, Good, Price )#\idx{at\_buyer/3@\verb#at_buyer/3#|ee}: This is true if trader T is at a
square which buys Good at Price.
 
\end{itemize}
 
Answers will be found in the file COLLIER\idx{COLLIER|ee}, but don't look until you have
tried the next section. You can \verb#restore# (not \verb#load#) this file.
 
 
\subsection{Coal trading}
 
With these predicates, can you define a version of \verb#act#\idx{act/4@\verb#act/4#|ee} that drives a
coal-trader round the Colliery Row circle? It will be like \verb#circler#\idx{CIRCLER|ee},
except that if he stops at a coal merchant, he should buy or sell as
appropriate. It is possible to make very complicated rules when trying
to squeeze out the maximum possible profit. Don't bother with that yet;
you probably don't know enough Prolog anyway. Just have him buy a fixed
amount at each wholesaler, if his lorry is empty; and sell a fixed
amount to each retailer, if his lorry is not empty. You can ignore the
need to buy fuel for the moment.
 
%sann
%{\it Note that at this point, students' \verb#act#s have to be
%completely reactive\idx{reactive predicates}, depending only on the games' current state.
%Until the
%predicates that alter the database\idx{database!in Traveller}
%are introduced, there is no way to store computed
%paths and plans for later use.}
 
One possible solution is in the file COLLIER\idx{COLLIER|ee}. I have pre-calculated the
amount of coal to buy on each cycle. Later, you can try to build a more
adaptable trader.
 
\idx{Traveller!how to write a trader|)ee}
 
\end{document}
