Prolog/KR                                         Version C-15
1. Introduction
1.1. The Language
Prolog/KR is an interactive  programming  system  designed  to
support  programs  manipulating  symbols and structures, espe-
cially  AI  (Artificial   Intelligence)   programs   embedding
knowledges  (including  control  knowledges);  KR  stands  for
Knowledge Representation.  Prolog/KR is equipped with some  of
the  basic  tools  used  in AI programs: backtracking, pattern
matching and data base manipulations.  Moreover,  manipulating
structures in Prolog is much simpler than in Lisp.  A program-
mer can start at a point closer to the solution.
Prolog/KR accepts more than one assertions  about  one  predi-
cate.  Each assertion is considered to express some knowledges
(possibly including control knowledges) about  the  predicate.
At  a  certain point of computation, when more than one asser-
tion can be used, the system tries them one by one -- if  some
inconsistency  arises  later,  the  system  backtracks  to the
latest choice point and tries the next assertion.
In representing knowledge, a procedural way and a  declarative
way  are  often  distinguished.   This  is however a matter of
degree.  In Prolog/KR, both way can be used.  Prolog/KR can be
used  as a procedural language as Lisp by providing every con-
trols explicitly.  In that  case,  no  automatic  backtracking
occurs,  and  thus  every computation is deterministic.  If no
controls are provided, on the other hand, automatic backtrack-
ing  does  its  job, and the computation is non-deterministic.
In usual cases, programming is done in a mixture of these  two
1.2. Notational Conventions
Lower case letters  are  usually  converted  into  upper  case
letters  on reading by the interpreter, i.e., there is no dis-
tinction between upper and lower case letters.   Nevertheless,
they  are distinguished in this manual.  Symbols which consist
only of lower case letters denote meta  symbols,  while  those
consist  of  upper  case  letters denote the symbol themselves
(they must be spelled as they appear in  this  manual).   When
they  are used in a mixture, it indicates that the word may be
abbreviated to a  word  consisting  of  only  the  upper  case
Example: "PrettyPrint" may be spelled either "PP" or  "PRETTY-
Meanings  and  functions  of  system  defined  predicates  are
explained in the following form:
                             -1-                  Introduction
Prolog/KR                                         Version C-15
         ........  ........
 is shown as a  sequence  of  Prolog/KR  variables,
possibly  followed  by  "..."  indicating  repetition  of  the
preceding argument.  Arguments are referred to by their  names
enclosed  in  "<"  and  ">" in .  Three distinct
prefixes are used for explanation:
*    This argument may be used both for input and output.
<    This argument must  be  an  output  variable.   In  other
     words,  a variable which has no value must be given as an
     argument to receive a value from the predicate.
>    This variable must be an input.  Giving an unbound  vari-
     able is erroneous.
Note: These conventions on variable prefix are  used  only  in
this  manual.   The  system  does  not distinguish those three
kinds of variables.
     FOO *e1 *e2
          FOO takes two arguments.  If FOO is  called  with  a
          wrong number of arguments, an error is issued.  Note
          that this rule is  applicable  only  to  the  system
          defined   predicates.    A  user  defined  predicate
          "fail"s when it is supplied with a wrong  number  of
     BAR >e1 *e2
          BAR also takes two arguments.   must be either a
          variable  which  already  has  some  value,  or non-
          variable object.  That is,  is an input argument
          which  expects to receive some value, rather than to
          return a value.
           may be anything, i.e., a variable or an object.
               (BAR (A B) *X)
               (BAR (A B) (C D))
          are legal, while
               (BAR *X *Y)
          is erroneous.
          Note: Although the current  version  of  the  inter-
          preter   treats  ">"  and  "*"  equally,  users  are
Introduction                 -2-
Prolog/KR                                         Version C-15
          recommended to use ">" when the variable is supposed
          to be an input, to increase the readability.
     TOng ›*e1®
          TONG takes zero or one argument.  TONG may be abbre-
          viated to TO.
     POO ›*e1®...
          POO takes any number of arguments (possibly zero).
     ZOO (*e1 *e2)
          ZOO's argument must be a list of two elements.
                             -3-                  Introduction
Prolog/KR                                         Version C-15
2. Objects
The syntax of Prolog/KR objects is described in this  section.
Unlike  other  Prolog  systems, Prolog/KR's objects (including
programs) are expressed as lists or atoms.  Thus, every object
except variables follows Lisp(Utilisp)'s syntax.
Although Prolog/KR supports all the Utilisp data types as  its
objects,  only the significant ones are described in this sec-
2.1. Variable
Variables are atoms (cf. 2.2.) which begin  either  with  "*",
">" or "<", e.g.,
          *X  >X  X are different variables.
Three kinds of prefixes are provided solely  for  readability.
The  system  does  not  distinguish those three kinds of vari-
Unlike most of other programming languages, variables are  not
space  holders.  Instead, variables are thought to be standing
for some Prolog/KR objects.  Variables are either undefined or
standing  for  some other objects.  When a variable stands for
an object, it  is  called  to  be  "instantiated"  and  it  is
equivalent  to  that  the  object  itself is there.  Even if a
variable is matched against another variable,  they  are  both
considered  to be uninstantiated and they will be instantiated
to the same object at the same time in the future.
 VAR *variable
     Succeeds if  has not been instantiated yet.  If
       has  already  been  instantiated  or is not a
     variable at all, then it fails.
 PREFIX >string ...
     Changes  the  variable  prefix  to  one   of   ,
     ,  ...  Only the first characters in the strings
     are effective.
          (PREFIX "@@" "*")
     changes the variable prefix to one of "@" and  "*".   The
     initial state of Prolog/KR is
          (PREFIX "*" ">" "<")
There is another kind of variable called  an  anonymous  vari-
able,  which  is  just  like  a variable except that it has no
Objects                      -4-
Prolog/KR                                         Version C-15
identity.  An anonymous variables is written as
and each occurrence of anonymous variable stands for different
     (= (? ?) (A B))     succeeds
     (= (* *) (A B))     fails
The anonymous variables are to  be  used  where  there  is  no
interest about the object.
CAR is a predicate to return the  first  element  of  a  list.
Since  there is no interest about the rest of the list, "?" is
2.2. Atom
An atom is either a symbol,  a  number  or  a  string.   Among
these, only symbols can be used as predicate names.
A symbol consists of a sequence of characters  except  special
      " ", "(", ")", "›", "®",  ";", "/", """", "'"
Above special characters may be used in a symbol provided that
it  is  preceded by "/".  Here is a summary of meanings of the
special characters:
     " "  delimiter
     "("  beginning of a list
     ")"  end of a list
     "›"  super left parenthesis
     "®"  super right parenthesis
     ";"  beginning of a comment (until the end of the line)
     "/"  escape character
     """" beginning and end of a string
     "'"  quoter of a pattern
Examples of symbols:
          THESE  ARE  SYMBOLS.  A.B  1+  /(A/)
Examples of numbers:
          12345  3.14159  1.0E-5  -0
                             -5-                       Objects
Prolog/KR                                         Version C-15
Examples of strings:
          "123"  "Strings must be surrounded by ""."
 ATOM >x
     Succeeds if  is an atom.  Otherwise, it fails.
2.3. List
Programs and structured data are expressed in lists.   A  list
is  a  sequence  of  objects  (including  lists)  enclosed  in
parentheses.  Dotted notation is used to express the rest of a
list.   For  example, "(A . *X)" matches any list which begins
with "A".  See the next section about the usage of the  dotted
notations in pattern matchings.
Examples of lists:
          (LISTS MAY CONTAIN *VAR 123 "string" ...)
          (THIS IS A DOTTED . PAIR)
2.4. Program
A Prolog/KR program consists of predicate calls and  predicate
definitions  and  both  are  expressed  in lists.  A predicate
definition consists of one or more assertions.  One  chunk  of
knowledge  is  called  an assertion and is added to the system
using ASSERT:
          (ASSERT (FALLIBLE *X) (HUMAN *X))›1®
This assertion means:
     *X is FALLIBLE if *X is HUMAN.
Procedurally, it is equivalent to:
     To execute (FALLIBLE *X), execute (HUMAN *X).
When an assertion is added to the system, it is merged into  a
proper  position  in the corresponding definition.  The detail
is described in chapter 5.
   ›1® This is an example of a predicate call (as well  as  an
assertion)  whose predicate name is ASSERT and whose arguments
are (FALLIBLE *X) and (HUMAN *X).
Objects                      -6-
Prolog/KR                                         Version C-15
3. Pattern Matching
Pattern matching (usually called "unification" in  Prolog)  is
the  basic  mechanism  of calling predicates in Prolog.  Vari-
ables may occur anywhere in the caller  and  the  callee,  and
there  is  no  distinction between their roles.  Variables may
match any Prolog/KR objects including other variables or lists
which have variables as their elements.
Since variables may be instantiated to an  object  which  con-
tains  variables,  it  is possible to define a value partially
and postpone  defining  the  rest  until  further  computation
determines it.  One of the most significant examples to demon-
strate this feature is APPEND which appends two lists:
          (ASSERT (APPEND () *ANY *ANY))
          (ASSERT (APPEND (*CAR . *CDR) *ANY (*CAR . *REST))
                  (APPEND *CDR *ANY *REST))
Under the above definition (see the chapter 5.  to  understand
what the above means), a predicate call,
          (APPEND (A B) (C D) *X)
proceeds as follows:
          (APPEND (A . (B)) (C D) (A . *REST_0001))
             where *REST_0001 is determined by
                (APPEND (B) (C D) *REST_0001)
          (APPEND (B . ())  (C D) (B . *REST_0002))
             where *REST_0002 is determined by
                (APPEND ()  (C D) *REST_0002)
          (APPEND () (C D) (C D))
The result of APPEND is first (A . *REST_0001); then  (A  B  .
*REST_0002); and finally (A B C D).
Note that in the above example, dotted notations  play  impor-
tant  roles.   In  the  pattern "(*CAR . *CDR)", it is used to
decompose a list into its so-called car part and so-called cdr
part.   In the pattern "(*CAR . *REST)", on the other hand, it
is used to do the reverse, that is, to  compose  a  list  from
*CAR  and  *REST.  Note that *REST was not defined at the time
of the composition.  Note also that if APPEND is  used  rever-
sally  as  (APPEND  *X (C D) (A B C D)), the roles of the pat-
terns also are reversed.
 MATCH *x *y
 = *x *y
     Tests if  and  can be  matched.   If  the  matching
     succeeds,  variables  in    and    are instantiated
     accordingly.  Otherwise, MATCH (or =) fails.
     CAUTION: If you execute (MATCH *X (F  *X)),  it  succeeds
                             -7-              Pattern Matching
Prolog/KR                                         Version C-15
     and results in instantiating *X to (F (F (F (F .....
 EQ >x >y
     Tests if  and  are the same objects (in  the  sense
     of  Lisp's  EQ).   It  does not suffice that they are the
     same patterns.
          (EQ A A)                     succeeds
          (EQ (A B C) (A B C))         fails
          (AND (= *X A) (EQ *X A))     succeeds
          (EQ *X A)                    fails
3.1. Extended Features
3.1.1. Quoting Patterns
Sometimes it is desired that a certain pattern does not  match
any variables.›2® The pattern should be quoted by "'" for that
purpose.   The  quoted pattern only matches patterns which are
     (= 'A *X)             fails
     (= 'A A)              succeeds
     (=  A *X)             succeeds
     (= '(A B C) '(A B C)) succeeds
     (= '(A B C) (A B *X)) fails
     (= '*X *X)            succeeds
     (= '*X *ELSE)         fails
   ›2® For example, a negative information is  expressed  with
so that (CAN PENGUIN FLY)  fails.   But  if  you  leave  these
assertions as they are, even
     (CAN *X FLY)
which is supposed to be a query to search for a flying object,
fails  before  reaching  HAWK.   To avoid this phenomenon, the
previous assertion must be changed to:
so that (CAN *X FLY) does not match (CAN  'PENGUIN  'FLY)  but
Pattern Matching             -8-
Prolog/KR                                         Version C-15
     (MEMBER A  (*X B C))  succeeds
     (MEMBER 'A (*X B C))  fails
Quote can be used as a  escape  character  of  an  atom  which
incidentally begins with one of the variable prefixes.
Note: predicates *, >, >=, < and <=  should  be  used  without
         (* 512 256 *X)
         (> *X *Y)
3.1.2. Executing Predicates within a Pattern
A list which begins with "!" is executed  during  the  pattern
matching  unless  the  pattern is inside another pattern which
matched a variable.  A variable with no names, usually "*", in
the  rest  of the pattern are first instantiated to the target
of the pattern matching, and then  the  pattern  is  executed.
For example, a pattern
     (! MEMBER * (FOO BAR))
matches either FOO or BAR, for
     (MEMBER * (FOO BAR))
is executed with * instantiated to the target of the matching.
Using this feature, a pattern which  matches  only  a  pattern
whose first element is a variable may be expressed as:
     ((! VAR *) . *ANY)
Only the first prefix defined by PREFIX (the default  is  "*")
is  considered  to  be the variable to get the value, i.e. the
target of the pattern matching.  Thus after executing  (PREFIX
"@" "#"), "@" is the variable to be instantiated.
Note that no backtracking occurs after  finishing  the  execu-
tion.  Therefore,
     (AND (= (! MEMBER * (FOO BAR)) *X)
          (= *X BAR))
fails, for * (and thus *X) is bound to FOO once and for all.
Note: Variables instantiated during the execution of the  pat-
tern  may  be unbound on exit.  Particularly, the value of "*"
is, due to the obvious reason, local to the pattern, and hence
invisible  from outside.  For the value of "*" to be exported,
it must be copied to another variable, e.g.,
     (! AND (VAR *) (= * *THE-VARIABLE))
                             -9-              Pattern Matching
Prolog/KR                                         Version C-15
Executable patterns can also be used to simulate  "functions".
For example, a function FACT (factorial) is defined as:
         (! COND ((= *N 0) (= * 1))
                  (TIMES *N (! FACT (! SUB1 *N *) *) *®
Note  the  nesting  of  executable  patterns.   To  show   the
correspondence  between  "!"s  and  "*"s,  a  suffixed version
(although it is not allowed) of the same example follows:
         (!a COND ((= *N 0) (= *a 1))
                   (TIMES *N (!b FACT (!c SUB1 *N *c) *b) *a®
Suppose FACT is called by
     (FACT 5 *F)
the following process takes place:
   1. *N = 3
   2. *a = *F
   3. (TIMES 3 (!b FACT (!c SUB1 *N *c) *b) *F) is executed
   4. (FACT (!c SUB1 3 *c) *b) is executed
   5. (SUB1 3 *c) is executed
   6. *c = 2
   7. ....
   8. *b = factorial(2) = 2
   9. *F = 6
For more convincing usage of the  executable  pattern,  confer
the description of SELECT.
Notes on ' and !: ' and ! are something like Lisp's QUOTE  and
EVAL.  ' prevents ! to be executed.
    (ASSERT (P (! ADD1 1 *)))
    (P 2)
To prevent ! to be executed at the time of the  assertion,  it
must be quoted as:
    (ASSERT (P '(! ADD1 1 *)))
    (ASSERT (P 'A))
is asserted as:
Pattern Matching             -10-
Prolog/KR                                         Version C-15
    (P A)
rather than:
    (P 'A)
To assert the latter, ' must be doubled:
    (ASSERT (P ''A))
                             -11-             Pattern Matching
Prolog/KR                                         Version C-15
4. Interpreter
4.1. Top Level Loop
At the top level of the Prolog/KR system, the  interpreter  is
waiting for user's input.  If a list is typed in, it is inter-
preted (executed) and, usually, the list is echoed  back  with
variables  instantiated  according to the result of the execu-
tion.  For example, suppose
          (PLUS 1 2 *)
is typed in, then
          (PLUS 1 2 3)
is printed back by the  interpreter.   If  the  execution  has
failed, "NIL" is printed instead.  For example,
          (PLUS 1 2 5)
Since every inputs  are  executed,  even  the  definitions  of
predicates  must  be  provided  in the form of predicate calls
(cf. section 5).  For example, FACT may be defined as:
          (ASSERT (FACT 0 1))
          (ASSERT (FACT *N *F)
                  (SUB1 *N *N1) (FACT *N1 *F1)
                  (TIMES *N *F1 *F))
In  this  case,  the  interpreter  acknowledges  simply   with
"ASSERTED" instead of printing the whole assertion back.
For typing conventions, extra right parentheses  are  ignored.
Super parentheses "›" and "®" are also available:
     (PRINT (A (B®
     (PRINT ›A (B®)
     Returns the last input.  LAST-INPUT  is  defined  as  the
     same  form  as  user defined predicates so that it can be
     edited and re-executed.  Note that the execution must  be
     done in the editor, since once you get out of the editor,
     the last input becomes "(EDIT LAST-INPUT)".
     Returns the last result typed out by the interpreter.  To
     see  the  detail of the result which had been abbreviated
     to "?", type:
          (GRIND (! LAST-RESULT *))
The Interpreter              -12-
Prolog/KR                                         Version C-15
     Of course, this does not change LAST-RESULT.
     Transfers the control to the top level loop.
     Initiates  the  top  level  loop.   Unlike   TOP,   which
     transfers  the  control  to  the top level of the current
     loop, PROLOG initiates a new loop, nested inside the  old
     Exits from a loop initiated by PROLOG and returns to  the
     previous status.
4.1.1. Executing the OS Command
If a line begins with a symbol, not a list, then the  line  is
regarded  as a OS command.  Any OS command except command pro-
cedures and safe commands can be called.
lists the contents of FOO.VDATA(BAR).  ":" in the above  exam-
ple is a prompt of the top level.
Pressing the break key quits the execution of the OS  command;
the control returns to the top level of Prolog/KR.
4.2. Error Handling
In case of errors, the interpreter  automatically  enters  the
stepper, where the status of the execution can be examined.  Q
command or "(TOP)" transfers the control to the top level.
The standard behavior on error described above can be  changed
by defining a predicate ERROR, which is called on error.
 ERROR >message >object
 STANDARD-ERROR-HANDLER >message >object
     Prints  followed by , where  is
     a string and  is a Prolog/KR object.
     Behavior of the error handler can  be  defined  for  each
     specific  error.   Since the first argument of ERROR is a
     message (string), the type of the error can  be  detected
     by the argument.
          (ASSERT (ERROR *MES *OBJ)
               (SELECT *MES
                             -13-              The Interpreter
Prolog/KR                                         Version C-15
                    ("UNDEFINED PREDICATE" (FALSE))
                    ( ..... )
                    (? (STANDARD-ERROR-HANDLER *MES *OBJ)))
Here is a list of messages of errors:
     "INVALID ARGUMENT TO predicate-name"
     "INVARID ARGUMENT LENGTH TO predicate-name"
4.3. Attention Handling
To abort the execution of a program, press the  break  key  on
the  terminal;  then the interpreter enters the stepper, where
some commands are accepted.  To resume the execution, issue  a
command  "F" meaning "finish the execution".  However, to con-
tinue exactly from the place of the break is almost  hopeless.
The  very  predicate  which was about to be called at the time
may not be completed properly.  If the break  key  is  pressed
inside   the  editor,  on  the  other  hand,  the  control  is
transferred to the top level (command interpreter) of the edi-
The standard behavior described above can be changed by defin-
ing  a predicate ATTENTION, which is called when the break key
is pressed.  The execution suspended by the break  is  resumed
after executing the body of ATTENTION.  Again, the very predi-
cate which was about to be called at the time of the break may
not be completed properly.
     Enters the stepper.
The Interpreter              -14-
Prolog/KR                                         Version C-15
5. Defining and Modifying Predicates
 ASsert (>predicate-name . >args) ›>predicate-call®...
     Adds  the  assertion  to  the  corresponding  definition.
     Since  there may be more than one assertion to one predi-
     cate, the word "definition" is used to regard  the  whole
     collection of assertions about the predicate.
     Example: (ASSERT (FALLIBLE *X) (HUMAN *X))
     ASSERT merges the assertion into  a  proper  (but  system
     defined)  position  in  the  definition.  The position is
     decided so that special cases appear  earlier  than  more
     general  ones.  If the automatic ordering is not desired,
     Note: When you make assertions on system  defined  predi-
     cates,  they  hide  the  system's  definitions  until the
     assertions are RETRACTed.
 AssertA (>predicate-name . >args) ›>predicate-call®...
     Just like ASSERT except for that it adds the assertion at
     the top of the corresponding definition.
 AssertZ (>predicate-name . >args) ›>predicate-call®...
     Just like ASSERT except for that it adds the assertion at
     the end of the corresponding definition.
     If  is a symbol, then all the assertions about 
     are retracted.
     If  is a list, then the first assertion whose  head-
     ing  matches  the  pattern  is retracted.  Note that (FOO
     BAR) matches (FOO *X).  Therefore,
          (RETRACT (FOO BAR))
     may retract an assertion which begins with (FOO *X).   To
     avoid the case, quote the pattern as:
          (RETRACT (FOO 'BAR))
          (RETRACT '(FOO BAR))
Usually,  the  definitions  of  predicates  are  added   using
ASSERTs.   But sometimes it is more convenient to override the
previous  definitions.   Particularly  when  definitions   are
loaded  from  a  file, it is rarely intended that loading from
the same file twice amounts to double  the  definitions.   The
latest loading should override the previous ones.
 DEFINE >name ›>definition-list®...
     Changes the definition of   to  s.
                             -15-         Predicate Definition
Prolog/KR                                         Version C-15
     The  previous  definition  of  is overridden by the
     new one.
      is to be given in the following form:
          ( . )
     For example,
          (DEFINE MEMBER ((*X (*X . *L)))
                         ((*X (*Y . *L)) (MEMBER *X *L)))
     is equivalent to:
          (RETRACT MEMBER)
          (ASSERT (MEMBER *X (*X . *L)))
          (ASSERT (MEMBER *X (*Y . *L)) (MEMBER *X *L))
     Note: (DEFINE name) is equivalent to (RETRACT name).
Calling a  predicate  which  lacks  definition  is  an  error.
Hence,  it  is  sometimes  useful  to define a predicate which
always fails.  As a special usage of DEFINE,
     (DEFINE name NIL)
is allowed to define such a predicate.  Of  course,  the  same
effect is produced by:
     (DEFINE name (() (FALSE)))
 SET >name >value ...
     Sets the definition of  so that  a  predicate  call
     (name *X) returns .
          (SET X 1)
     is equivalent to
          (DEFINE X ((1)))
          (RETRACT X)
          (ASSERT (X 1))
 DEFINITION >name *definition
     Retrieves the definition of .  For example,
          (DEFINE FALLIBLE ((*X) (HUMAN *X))
                           ((*X) (GOD *X)))
Predicate Definition         -16-
Prolog/KR                                         Version C-15
     sets *DEF to (((*X) (HUMAN *X)) ((*X) (GOD *X))).
     Example: ASSERTA can be defined as:
          (ASSERT (ASSERTA (*PRED . *ARGS) . *BODY)
                  (DEFINITION *PRED *DEFS)
                  (DEFINE *PRED
                          ((*ARGS . *BODY) . *DEFS)))
 LISting >name ...
     Prints the definition of  as (ASSERT ... )...
Notes on  the  definition  form:  Definition  of  a  predicate
appears  in different forms in ASSERT(A/Z), DEFINE, DEFINITION
and WITH.  Internally, it is stored in the form of DEFINE:
    (( . )
     ( . )
      ... )
For example, 'append' is stored as:
    (((() *X *X))
     (((*A . *X) *Y (*A . *Z))
      (APPEND *X *Y *Z)))
If we call it "definition-body", then each form  is  expressed
    (DEFINE  . )
    (WITH (( . ) ... ) ... )
                             -17-         Predicate Definition
Prolog/KR                                         Version C-15
6. Controls
Although Prolog/KR's default control  strategy  is  the  depth
first trial with backtracking, users can control the execution
using control predicates  provided  by  the  system.   Control
predicates  with no backtracking are called deterministic con-
trol predicates.  If  all  the  controls  are  provided  using
deterministic control predicates, then the system runs without
any backtrackings -- like Lisp.
6.1. Success and Failure
Prolog's control depends on "success" and "failure".  A predi-
cate call succeeds if and only if the following conditions are
all satisfied.
   1) There exists a definition (either system defined or user
   defined) for the predicate.  Otherwise, it is an error.
   2) The pattern of the caller matches  the  pattern  of  the
   callee.   If  they do not match, the behavior is determined
   whether the callee is system defined or not: if the  callee
   is  system  defined then it is an error, otherwise, it is a
   3) If the callee is the user  defined  predicate,  all  the
   predicate  calls  in the body of the callee succeed.  If it
   is a system defined predicate, the behavior is described in
   this manual.
On failure, the system backtracks and  tries  alternatives  if
any  (deterministic control predicates leave no alternatives).
No alternatives being left, the whole execution fails.
     Always fails and triggers backtracking.
          (AND (MEMBER *X (A B C))
               (PRINT *X)
     produces a result:
     where "NIL" indicates the failure of AND.
     Causes a failure of the caller  of  the  predicate  which
     contains FAIL in its body.  FAIL is to be used to express
     a negative information.   In  other  words,  if  FAIL  is
Controls                     -18-
Prolog/KR                                         Version C-15
     encountered  while  executing  a  body of a predicate, P,
     then P must be false.
     Example: NOT may be defined as:
          (ASSERT (NOT *PRED) *PRED (FAIL))
          (ASSERT (NOT ?))
 NOT >predicate
     Inverts the success and failure of  .   There-
     fore,  NOT succeeds when  fails and fails when
      succeeds.  Note that NOT do  not  instantiate
     any  variable because at least one failure occurs whether
     in  or at NOT itself.
     NOT is to be used only to  test  rather  to  return  some
          (NOT (P *X))
          For all, *X (P *X) is false.
     rather than
          Exists *X such that (P *X) is false.
     Therefore, for example,
          (NOT (= *X A))
     fails while
          (AND (= *X B) (NOT (= *X A)))
     Immediately succeeds, but only  once  --  TRUE  does  not
     succeed  in  case  of  backtracking.   Therefore TRUE and
     FALSE cannot be used to construct a loop:
          (AND (TRUE) (PRINT DOING) (FALSE))
     is executed only once.
 ONBT >predicate-call
     Does nothing during the forward  execution.   When  back-
     tracking  propagates  up  to  ONBT,  on  the  other hand,
       is  executed;  backtracking   continues
     regardless of the result.
     Note that (ONBT (TRUE)) has no effect at all  because  it
     does nothing even in the case of backtracking.
                             -19-                     Controls
Prolog/KR                                         Version C-15
     Throws backtracking alternatives away  up  to  a  certain
     point  (up  to the caller of the predicate which contains
     CUT in its body).
     Note: This predicate is suggested,  by  the  implementor,
     not  to  be used.  CUT is provided only for compatibility
     with other Prolog systems.
6.2. Non-deterministic Controls
Since non-deterministic (this word is used  as  a  synonym  of
"with  backtracking"  in  this  manual) control is the default
strategy used in Prolog, all the control predicates  described
in  this  section  may  be eliminated by defining extra predi-
cates.  Nevertheless they are provided for the sake of simpli-
city and efficiency.
 AND ›>predicate-call®...
     Executes s from left to right with  back-
     tracking  in  case of failures until all of them (and the
     rest of the execution) succeed.  This is also the default
     mode  of  executing a body of a predicate.  Thus the fol-
     lowing two assertions have exactly the same meaning.
          (ASSERT (INTERSECT *X *Y *E)
                  (MEMBER *E *X) (MEMBER *E *Y))
          (ASSERT (INTERSECT *X *Y *E)
                  (AND (MEMBER *E *X) (MEMBER *E *Y)))
     In the above example, INTERSECT returns elements  of  the
     intersection  of  X  and  Y  one  by  one until INTERSECT
     finally fails.  For example,
          (AND (INTERSECT (A B C) (B C D) *E)
               (PRINT *E)
     Note that "(AND)" immediately succeeds.
 OR ›>predicate-call®...
     Executes s from left to right  until  one
     of  them  succeeds.   In  case of later backtracking, the
     alternatives of the  which succeeded most
     recently   are   tried.   If  they  all  fail,  the  next
     , if any, is tried.   If  no   remains, OR fails.
     OR can be eliminated by providing extra  predicate.   For
Controls                     -20-
Prolog/KR                                         Version C-15
          (ASSERT (P *X) (OR (Q *X) (R *X)))
     is equivalent to:
          (ASSERT (P *X) (Q-OR-R *X))
          (ASSERT (Q-OR-R *X) (Q *X))
          (ASSERT (Q-OR-R *X) (R *X))
     Note that "(OR)" fails.
6.3. Deterministic Controls
Control predicates described in this  section  somewhat  limit
the scope of backtracking.
 IF >predicate-call >then-part ›>else-part®
     If  succeeds, then    is  exe-
     cuted.   Otherwise,    is  executed; if  is omitted, (TRUE)  is  assumed  and  IF  succeeds.
     Once    succeeds,  it  will not be backtracked
     later, nor  will not be executed.
          (ASSERT (MAX *X *Y *M)
                  (IF (> *X *Y) (= *M *X) (= *M *Y)))
     is equivalent to:
          (ASSERT (MAX *X *Y *X) (> *X *Y))
          (ASSERT (MAX *X *Y *Y) (<= *X *Y))
     Note that the above example is NOT equivalent to:
          (ASSERT (MAX *X *Y *X) (> *X *Y))
          (ASSERT (MAX *X *Y *Y))
 DO ›predicate-call®...
     Executes s regardless of their success or
     failure.   In  other  words, arguments of DO are executed
     one by one and failing to execute one of  them  does  not
     cause  backtracking;  the  execution proceeds to the next
     Example: The result of
         (DO (MEMBER *X (1 2 3))
             (PRINT *X)
             (PRINT NEXT))
                             -21-                     Controls
Prolog/KR                                         Version C-15
         (DO (MEMBER *X ?) (PRINT ?) ? . ?)
 DAND ›>predicate-call®...
     Executes s one by one until all  of  them
     succeeds.  If one of them fails, DAND fails without back-
          (DAND (OR (PRINT A) (PRINT B)) (FALSE))
     fails after printing only A.
          (DAND p q r)
     is equivalent to:
          (IF p (IF q (IF r (TRUE) (FALSE)) (FALSE)) (FALSE))
 DOR ›>predicate-call®...
     Executes s one by one until one  of  them
     succeeds.   No alternatives are tried on later backtrack-
     ing; DOR fails then.
          (DOR a b c)
     is equivalent to:
          (IF a (TRUE)
             (IF b (TRUE)
                (IF c (TRUE) (FALSE))))
 COND ›(>predicate . >body)®...
     Tries s from left to right until one  of  them
     succeeds,  and then the corresponding  is executed.
     Although backtracking may occur during the  execution  of
     ,  it  does  not  propagate to  or other
     alternatives; if  fails,  then  COND  fails.   Once
       succeeds  COND  succeeds and no more alternatives
     are tried on later backtracking.
                ((PRINT B) (PRINT SECOND-CHOICE) (FALSE))
                ((PRINT THIS-WONT-BE-EXECUTED))) results:
Controls                     -22-
Prolog/KR                                         Version C-15
 RETURN ›>predicate-call®...
     Fixes the choice of  the  alternatives  of  predicate  to
     s.  This predicate is to be used to simu-
     late a kind of macro.  For example:
          (ASSERT (>= *X *Y)
                  (RETURN (OR (> *X *Y) (= *X *Y))))
     is used to achieve equivalence between
          (AND ... (>= *X *Y) ...)
          (AND ... (OR (> *X *Y) (= *X *Y)) ...)
     regarding backtracking.  Even though there may be another
     assertion  about  >=,  no alternatives on >= are tried in
     case of backtracking.
     A more convincing but more complex  example  is  defining
     DOR  using  RETURN  (the  semantics of DOR has been given
     earlier in this section):
          (ASSERT (DOR *P . *REST)
          (ASSERT (DOR *P . *REST) (RETURN (DOR . *REST)))
          (ASSERT (DOR) (RETURN (FALSE)))
     The second and the third RETURN  are  redundant  in  this
     example.   A  pattern  which matches the second assertion
     never matches the third one.  RETURN executed in the last
     alternative has no effect.
     Note: Do not use RETURN or FAIL in RETURN as:
     It may return or fail too many levels.
 SELECT *pattern (*pattern1 . >body1) ...
     Tries to match  to , , etc.,
     until one of them can be matched.  Like COND, no alterna-
     tive patterns are searched on  backtracking.   A  pattern
     corresponding to "(TRUE)" in COND is, of course, "?".
     Example: a deterministic version of APPEND can be defined
          (ASSERT (APPEND . *A)
                  (SELECT *A
                         ((() *X *X))
                         (((*B . *X) *Y (*B . *Z))
                          (APPEND *X *Y *Z))))
                             -23-                     Controls
Prolog/KR                                         Version C-15
     Another example: branching on the input can be  expressed
          (AND (READ *INPUT)
               (SELECT *INPUT
                    (YES (DO-YES))
                    (NO  (DO-NO))
                    (?   (HESITATE))))
     Note that "?" matches anything.
     If some of the branches are the same, an executable  pat-
     tern is be convenient to use:
         (SELECT *INPUT
              ((! MEMBER * (YES Y)) (DOING YES))
              ((! MEMBER * (NO N))  (DOING NO))
              (? (HESITATE)))
     rather than:
         (SELECT *INPUT
              (YES (DOING YES))
              (Y   (DOING YES))
              (NO  (DOING NO))
              (N   (DOING NO))
              (?   (HESITATE)))
6.4. Repetition
 FOR-ALL >predicate-call >body ...
     Tries s for each alternative  of  .
     FOR-ALL succeeds if and only if
           logically implies s.
     In other words, FOR-ALL tests whether  all  solutions  of
       also  satisfy .  No variables are
     instantiated inside FOR-ALL.
          (AND (FOR-ALL (MEMBER *X (A B C)) (PRINT *X))
               (VAR *X))
     succeeds after printing:
     Note that (VAR *X) succeeds, because *X is left uninstan-
Controls                     -24-
Prolog/KR                                         Version C-15
     When s fail, FOR-ALL immediately fails without try-
     ing the next alternative of .  For example,
          (FOR-ALL (MEMBER *X (A B C)) (PRINT *X) (FALSE))
 CANDIDATES *variable >predicate-call ...
     Instantiates  to a list of all  the  values  of
      which satisfies s.  
     must be an uninstantiated variable on entrance.
     Example1: Provided that EVEN-NUMBER  succeeds  only  when
     its argument is an even number,
          (CANDIDATES *X (MEMBER *X 1 2 3 4 5)
                         (EVEN-NUMBER *X))
     sets *X to (2 4).
     Another example: INTERSECTION and UNION may be defined as
                  (CANDIDATES *RESULT
                              (MEMBER *RESULT *X)
                              (MEMBER *RESULT *Y)))
          (ASSERT (UNION *X *Y *RESULT)
                  (CANDIDATES *RESULT
                              (OR (MEMBER *RESULT *X)
                                  (MEMBER *RESULT *Y))))
     Note that (INTERSECTION (A B) (B C) (B)) fails under  the
     above  definition,  because,  for example, (MEMBER (B) (A
     B)) fails.  CANDIDATES must be used to produce a  result,
     not to test the result.
 ACCUMULATE *structure >predicate *variable
     Instantiates  to  a  list  of    the
     value  of  which  is  determined  by  each alternative of
     .  ACCUMULATE is a generalized version of CAN-
     DIDATES.  In fact, CANDIDATES can be defined as:
          (ASSERT (CANDIDATES *X *P)
                  (ACCUMULATE *X *P *X))
     Example: Here is a new definition of INTERSECTION accord-
     ing to which (INTERSECTION (A B) (B C) (B)) succeeds.
              (ACCUMULATE *TEMP
                          (AND (MEMBER *TEMP *X)
                             -25-                     Controls
Prolog/KR                                         Version C-15
                               (MEMBER *TEMP *Y))
Note: On the current implementation, some predicates cannot be
used  inside  the predicates described so far in this section.
They are NOT, DOR, COND, POR, RECORD and ERASE.  This rule  is
not applicable to the following predicates.
 LOOP ›predicate-call®...
     Repeats  s  until   EXIT   is   executed.
     "while-do"  and  "repeat-until" are considered to be spe-
     cial cases of LOOP.
          (ASSERT (WHILE-DO *P *BODY)
                  (LOOP (IF *P (TRUE) (EXIT)) *BODY))
                  (LOOP *BODY (IF *P (EXIT))))
     Exits from the innermost LOOP.
6.5. Pseudo Parallelism
A limited version of pseudo parallel computation is  supported
in current implementation.
 POR >predicate-call ...
     Executes s in  a  pseudo  parallel  mode.
     Usually,  each  is executed one step (one
     predicate invocation) and then another one  is  executed.
     As  the  name  suggests,  there is no interaction between
     s.  They are executed independently  even
     if  they share the same variables; those variables are to
     be thought as different ones.
     When one of  the  s  succeeds,  then  POR
     succeeds  once and for all.  No alternatives are tried on
     later backtracking.
     If a control  predicate  (except  AND,  OR  and  NOT)  or
     RECORDED  or ERASE is called within POR, the call is com-
     pleted before other s are executed.   For
          (AND (POR (AND (PRINT A) (PRINT B))
                    (OR (PRINT OR-1) (PRINT OR-2))
                    (PRINT C))
Controls                     -26-
Prolog/KR                                         Version C-15
     Note that the same rule is applied  when  POR  is  called
     within POR.
6.6. Non Local Exit
 CATCH >predicate-call
     Executes .  If THROW is  executed  during
     the execution of , the control may return
     to CATCH if the following conditions are satisfied:
        1)  matches the argument of the THROW.
        2) The CATCH is the inner-most one which satisfies 1).
     In this case, variables in   are  instan-
     tiated through the pattern matching.
     If  terminates normally, either with suc-
     cess or failure, CATCH terminates with the result.
 THROW >pattern
     Transfers the control up to the  inner-most  CATCH  whose
     argument matches .
     Example: Here is a definition  of  DOR  using  CATCH  and
          (ASSERT (DOR . *X)
               (CATCH (FOR-ALL (MEMBER *PRED *X)
                        (IF *PRED (THROW (FOR-ALL . ?)))))
6.7. Co-routine
In Prolog/KR, co-routines are divided into a  producer  and  a
consumer.  A producer is a normal Prolog/KR predicate which is
supposed to succeed with more than one result.  For example,
     (MEMBER *X (A B C))
can be used as a producer which returns *X=A, *X=B  and  *X=C.
A  consumer,  on the other hand, does special things: initiate
the producer and then get results from it.
 INITIATE >predicate-call *name
     Creates a producer with    and  name  the
     producer  uniquely.   The  unique  name  is  returned  to
                             -27-                     Controls
Prolog/KR                                         Version C-15
          (INITIATE (MEMBER *X (A B C)) *M)
 NEXT >producer . >pattern
     Gets one result from .  To be more precise, the
     producer  is  forced to backtrack to another result, then
     the pattern which was given as the first argument of INI-
     TIATE  is  instantiated  with the result, and finally the
     pattern is matched with .
     NEXT does not produce another result on backtracking;  it
     fails  instead.   The fact that the producer is called is
     not undone on backtracking  either.   Therefore,  if  the
     same  NEXT  is entered more than once (after failing once
     or more), it produces the next result.
     Example: the producer which was initiated by:
          (INITIATE (MEMBER *X (A B C)) *M)
     can be called by:
          (NEXT *M *Y (A B C))
          (NEXT *M *Y ?)
     In both cases, *Y is instantiated to A on the first call;
     to B on the second call, and so on.
     As you can see by the example, the last argument of NEXT,
     "(A  B C)", is not necessary for normal uses.  Hence, for
     the convenience  of  the  programmer,    may  be
     shorter  than the actual pattern.  In that case, the rest
     of the pattern of the producer is ignored.  The  previous
     producer can thus be called also by:
          (NEXT *M *Y)
Controls                     -28-
Prolog/KR                                         Version C-15
7. Data Base Facilities
In Prolog, predicate definitions can be regarded as a  collec-
tion of assertions to a data base.  Prolog/KR supports facili-
ties to construct a kind of a hierarchical data base.
7.1. Internal Data Base
Prolog/KR provides an indexed internal data base which is com-
pletely separated from predicate definitions.
Since the internal data base is indexed by its contents  (only
by  symbols and numbers), it guarantees quick retrieval of the
contents.  This is the main difference from the top level data
base  which  consists  of predicate definitions; the top level
data base is indexed only by predicate names.
 RECORD >pattern
     Adds  into the internal  data  base.   
     must  be  a  list  whose first element is a symbol (other
     elements may be any objects including variables).
     IMPORTANT: The effect of RECORD  is  undone  in  case  of
 RECORDED >pattern
     Retrieves one element in the  internal  data  base  which
     matches .  In case of backtracking, the next one
     is retrieved.  The order of the retrieval is undefined.
 RECORDING >pattern >daemon
     Creates a daemon which is activated when something  which
     matches  is RECORDed.  The daemon vanishes after
     one activation.
               (PRINC "Turing is a human.")
               (RECORD (FALLIBLE TURING)))
               (PRINC "Turing is fallible."))
          Turing is a human.
          Turing is fallible.
     If there already exists a datum which matches  ,
     the daemon is immediately activated.
 ERASE >pattern
                             -29-         Data Base Facilities
Prolog/KR                                         Version C-15
     Erases one datum which matches  .   Another  one
     will be erased in case of backtracking.
7.2. Worlds
Prolog/KR consists of at least two  partitions  of  definition
spaces;  one of them consists of system defined predicates and
the  other  is  the  default  space  for  the  users   (called
STANDARD-WORLD).   A user can construct more worlds explicitly
or implicitly.  Predicates defined within other worlds  except
parent  worlds cannot be called directly.  They must be called
          (WITH name-of-the-world (predicate .... ))
The following picture gives a rough idea of relations  between
              -------------        -----------
              |  WORLD-A  |        | WORLD-A |
           ------------------    ---------------
           | STANDARD-WORLD |    |   WORLD-B   |
A world can be created explicitly (CREATE-WORLD) or implicitly
(WITH),  referred  to (WITH), saved (DUMP), loaded from a file
(LOAD-WORLD) and destroyed (ERASE-WORLD).  Suppose, for  exam-
ple, worlds A and B contain the following definitions:
          A contains definitions of PA1, PA2
          B contains definitions of PB1, PB2
And suppose that the current world is A, then PA1 and PA2  can
be called directly, but PB1 and PB2 must be called as follows:
          (WITH B (PB1 ... ))
          (WITH B (PB2 ... ) (PA1 ...))
Note that PA1 is visible even when the world B is opened.   In
other words, a inner world inherits predicate definitions from
outer  worlds.   The  inheritance  is  dynamically  determined
unlike other programming languages or knowledge representation
 WITH >world ›>body®...
     If  is a name of a world (i.e.,  a  symbol),  then
     WITH  executes  s within the world.  If the name of
     the world is a new one, then a new world is created.
     If  is a list of predicate definitions, then those
     definitions  become  visible only while s are being
     executed.  Once the system exits from  the  world,  those
     definitions are not only invisible but also destroyed.
Data Base Facilities         -30-
Prolog/KR                                         Version C-15
     Predicate definitions given outside of WITH are effective
     only if they are not overridden by .
     Here is an example in which WITH is used to simulate glo-
     bal variables:
          (WITH ((X) (Y ((1))))
                (SET X A)        ; sets the value of X to A
                (X *X)           ; *X becomes A
                (Y *Y)           ; *Y becomes 1
 CREATE-WORLD >name ›>predicate-definition® ...
     Creates a new world called , which  initially  con-
     tains   predicate   definitions   given   by  s.
          (CREATE-WORLD PP
             (PRIN1 ((*OBJ) (PRINC *OBJ)))
             (PRINT ((*OBJ) (GRIND *OBJ))))
     creates  a  new  world  called  PP,  in  which  PRINT  is
     equivalent  to  GRIND except that escape character is not
     supplied.  Therefore,
          (WITH PP (PRINT /-/ A/ -))
          - A -
     while both
          (PRINT /-/ A/ -)
          (GRIND /-/ A/ -)
          /-/ A/ -
     Destroys the world  so that  it  no  more  contains
 LOAD-WORLD >file-name >name
     Loads definitions from  into a  world  .
     Since  there is no notion of a world once definitions are
     dumped into a file (cf. DUMP), the name of the world must
     be given explicitly when it is loaded from a file.
                             -31-         Data Base Facilities
Prolog/KR                                         Version C-15
     Returns the name of the current world.
Data Base Facilities         -32-
Prolog/KR                                         Version C-15
8. Debugging Aids
Prolog/KR has two  modes:  debugging  mode  and  non-debugging
mode.   In  debugging mode, some extra informations are saved.
For example, backtracing is effective  only  when  the  inter-
preter has been running in the debugging mode.
 DEBUG *mode
     Switches debugging mode according to : if  is
     ON,   then   the   interpreter  runs  in  debugging  mode
     thereafter; if  is OFF, then the  interpreter  runs
     in  non-debugging mode; if  is a variable, then the
     current mode (ON or OFF) is returned.
     Returns the history of  the  execution  (including  back-
     tracking) to .
8.1. Tracer
 TRACE ›>name®...
     Enables tracing of s.  The output of the tracer  is
     in the following form:
          level (predicate-call)
          level= (predicate-call)
     The former is printed when a predicate call is tried; the
     latter is printed when it succeeds.
     Enables tracing of all predicates.
 UNTRACE ›>name®...
     Disables tracing of s.
     Disables tracing of all predicates.
8.2. Stepper
The stepper is called via STEP.
 STEP >predicate-call ›>name®...
     Execute  in a  step-by-step  manner.   On
     each  step, the stepper requests for command(s) to deter-
     mine the next action.
     If s are supplied, the stepper stops  only  at  the
     entrances of s.
The stepper commands are:
                             -33-               Debugging Aids
Prolog/KR                                         Version C-15
     Continue step-by-step execution.
     Finish step-by-step mode and resume normal execution.
     Execute the body in normal mode and  return  to  step-by-
     step mode afterwards.
     Quit stepping and return to the top level.
     Backtrace the history of the execution.   BT  prints  the
     outlines,  while  BACKTRACE  prints  with details.  Debug
     mode must be on to use this command.
     Prettyprint the current goal.
     Execute the list.
8.3. Editor
The structure oriented editor Amuse is available in Prolog/KR.
To edit a predicate definition or a file, do
     (EDIT predicate-name)
     (EDIT "file-name")
You may also execute some editor commands on entrance by:
          (EDIT name commands ...)
You can use this feature to define some function to manipulate
function definitions.
 EDIT >name ›(›>editor-command® ›>argument®...)®
     Edits .  If  is a symbol, the  definition  of
       is  edited.   If  is a string, on the other
     hand, a file with that name is edited.  In that case, the
     top-level  scope  is  a list of the contents of the file.
     All the commands are the same in both cases.
8.3.1. Scope
The editor moves around the structure by shifting  its  atten-
tion.   The  range of the current attention is called "scope".
You can narrow the scope by moving down in the  structure,  or
widen it by moving up.
Debugging Aids               -34-
Prolog/KR                                         Version C-15
You can print the current scope by P command.  If  you  use  V
command  on  the other hand, a list which includes the current
scope as its top level element is shown.  Suppose you  are  at
the first pair of COND list:
     (COND ((ATOM X) Y)
           (T (CONS (CAR X) (APPEND (CDR X) Y))))
P prints
     ((ATOM X) Y)
while V prints
     (COND $$$ (T (CONS ? ?)))
Note: If "$$$" appears in a list used as an  example  in  this
section, the list is supposed to be showing one upper level of
the current scope.
8.3.2. The Stack
The editor has one stack to save  various  elements.   If  you
kill  or  copy  an  element, it is pushed into the stack.  The
contents of the stack may be shown by STACK command.   If  you
do  not  need  the  top-most  element  of the stack, it may be
removed by POP command.  Elements of the stack can be used  as
arguments  to  a  command, such as "F" and "R".  An integer at
the argument position designates the nth argument from the top
of the stack.
          I 1
inserts the topmost  element  on  the  stack  just  after  the
current scope.
CAUTION: If you want to give an integer itself as an argument,
quote it by "'", e.g. '3.
8.3.3. Pattern Matching and Variables
Patterns may appear as  arguments  to  F(find)  or  RA(replace
all),  e.t.c.  Unlike the top level, an atom which begins with
a character "&" is regarded as a variable in the pattern.   It
can match any objects.
For example, (&A &A . &B) matches any of
          (A A)
          (A A X Y Z)
          (XXX XXX XXX)
                             -35-               Debugging Aids
Prolog/KR                                         Version C-15
but not:
          (A *X)
          (A B C)
          (&1 &2)
Note that Prolog/KR variables are  not  treated  as  variables
inside the editor.  Note also that the pattern matching of the
editor is one way.
If variables appear in the arguments of RA command, the values
are  held until each replacement completes.  You can thus, for
example, change the order of arguments  of  all  the  function
calls of "F" by:
     RA (F &1 &2) (F &2 &1)
The above command changes
     (AND (F *X *Y) (F (F A B) (G 1 2)))
     (AND (F *Y *X) (F (G 1 2) (F A B)))
Note that (F A B) has not been changed, because RA is  applied
to the outer most pattern.
The first argument of "G" can be quoted by:
     RA (G &1 . &2) (G '&1 . &2)
8.3.4. How to Give Commands
Basically, there are two ways to give commands to the editor.
One, usually, editor reads commands from the terminal  with  a
prompt  "E:".  The user may input any number of commands (each
of them may followed by some arguments) and they are  executed
at once.
Two, they are given as the second argument to EDIT as:
which first print the  top  level  and  inserts  "(SOMETHING)"
after the first element before accepting further commands from
the terminal.
8.3.5. Basic Commands
Each  command  for  the  editor  consists  of  one   or   more
character(s),  possibly  with argument(s).  Basic commands are
Debugging Aids               -36-
Prolog/KR                                         Version C-15
defined as Prolog/KR predicates.  The name  of  the  predicate
begins  EC: (standing for Editor Command) followed by the com-
mand name.  For example, a insert command is called as:
     (EC:IN '(A B C))
Note that arguments of a command is evaluated in Utilisp.
Basic commands also have abbreviated form.  They can be  given
from  a  terminal  without parenthesis or "EC:".  For example,
the above insert command may also be invoked by:
     IN (A B C)
Arguments are not evaluated this time.
Commands are described in the following:
     Moves to the previous element (the opposite of N).
     Example: If the current scope is
          (A B $$$ D)
     "B" changes the current scope to B:
          (A $$$ C D)
 BI number1 number2
 (EC:BI number1 number2)
     Encloses elements (from th  to  th)  in
          BI 2 3
          (A B C D E F G)
          (A (B C) D E F G)
     Removes the parentheses enclosing the current scope  (the
     opposite of BI).
     Copies the current scope to the top of the stack.
     Deletes the current scope.  The new  scope  is  the  next
                             -37-               Debugging Aids
Prolog/KR                                         Version C-15
     element  which followed the deleted one.  If there exists
     none following, i.e., the deleted element  had  been  the
     last  element  of  the  list,  then the scope goes up one
 E name
 (EC:E name)
     Abandons the result of the current editing and shift  the
     object of editing to .
 F pattern
 (EC:F pattern)
     Moves to an  element  which  matches  .   If  no
     proper  element is found, EC:F returns NIL in Utilisp and
     fails in Prolog/KR.  If F had been  used,  on  the  other
     hand,  an  message  indicating the failure is printed and
     any commands following the same line are ignored.
     Moves to the next element which matches the pattern  most
     recently  given to  "F" command.  If no proper element is
     found,  EC:FN  returns  NIL  in  Utilisp  and  fails   in
     Prolog/KR.   If  FN  had been used, on the other hand, an
     message indicating the failure is printed  and  any  com-
     mands following the same line are ignored.
 I element
 IN element
 (EC:IN element)
     Inserts  just after the  current  element.   The
     scope is shifted to the inserted element.
 IB element
 (EC:IB element)
     Inserts  just before the current  element.   The
     scope is not changed.
     Kills the current element and  push  it  on  top  of  the
     stack.   The new scope is the next element which followed
     the killed one.  If there exists  none  following,  i.e.,
     the killed element had been the last element of the list,
     then the scope goes up one level.
     Moves to the last element of the current scope.
     Executes all the elements of  the  topmost  scope.   This
     command  is  intended  to be used while editing a file to
     reload changed definitions.
Debugging Aids               -38-
Prolog/KR                                         Version C-15
     Inserts a left parenthesis just before the  current  ele-
     ment.  The scope remains the same.
     Example: If the current scope is
          (A $$$ C)
     LI changes it to:
          (A ($$$ C))
 LEVEL number
 (EC:LEVEL number)
     Resets the printing depth to .  The default depth
     is 7.
     Moves to the next element.  If the current element is the
     last one, then an error is issued.
     Prints the current element without details.  Details  are
     printed  by "?".  The level of the printing is controlled
     by LEVEL.
     Prints the current element with details.
     Pops the stack.
     Restores the result of the editing  and  exits  from  the
 R element
 (EC:R element)
     Replaces the current scope by .
 RA pattern1 pattern2
 (EC:RA pattern1 pattern2 ›maximum-number-of-replacement®)
     Replaces all the elements of the current scope (including
     the  scope  itself) which match  by .
      is matched with the element on  each  replace-
     ment.   Hence,  variables  appearing  in    are
     replaced properly.  The scope is not changed by the  com-
                             -39-               Debugging Aids
Prolog/KR                                         Version C-15
     If  is supplied, then only
     the  first    patterns are
     Example: Suppose that the current scope is
           (P (T A) (T B) (T2 C))
     and you issue "RA (T &X) (TT &X)", then the result is:
           (P (TT A) (TT B) (T2 C))
 R1, R2, R3
     are all same as "RA" except that they change  only  first
     one, two or three elements respectively.
     Inserts a right parenthesis just after the current scope.
     Example: If the current scope is
          (A $$$ C)
     RI changes it to:
          ((A $$$) C)
     Restores the current result without exiting from the edi-
 SC name
 (EC:SC name)
     Stores the current result of editing to .   When  a
     file  is being edited,  must be a name of an exist-
     ing file, expressed as a string.
     Prints the contents of the stack.
     Moves to the top level of the definition, which  is  nor-
     mally a list of clauses.
 U symbol
 (EC:U symbol)
     Goes up in the structure up to a structure  which  begins
     with .  For example,
          U DEFINE
Debugging Aids               -40-
Prolog/KR                                         Version C-15
     goes up to a structure (DEFINE ...).
     Shows the current position by printing the  upper  level.
     The current scope is printed as "$$$".
 VAR character
 (EC:VAR character)
     Changes the variable prefix to .  The original
     variable prefix is "&".
 X predicate-call
 (EC:X predicate-call)
     Executes  and prints  the  result.   Like
     other  commands,  elements  in  the stack can be given as
      by specifying a number.  The number 0 is
     treated  specially by X; it designates the current scope.
     This feature is useful  when  a  file  is  being  edited.
     Since changing the contents of a file does not affect the
     loaded  definitions,  the  changed  definitions  must  be
     reloaded.   The  most simple way is to shift the scope to
     (DEFINE ...) and execute the command "X 0".
     Abandons editing and exit.  The  original  definition  or
     contents of the file are not changed.
     Prints the name of  the  predicate/file  which  is  being
 (E:MOVE number)
     Moves to the th element of the current scope.  If
     the  number  is 0, then the scope is shifted to the upper
     level.  And if the number is negative, the  elements  are
     counted from the end of the list.
     Here is an example list with commands to move to its ele-
     ments listed below:
          (FOO BAR POO ZOO TONG)
            |   |   |   |   |
            1   2   3   4   5
           -5  -4  -3  -2  -1
     If the corresponding element lacks (because the  list  is
     too  short), or (E:MOVE 0) is attempted at the top level,
     then  E:MOVE  returns  NIL  in  Utilisp  and   fails   in
                             -41-               Debugging Aids
Prolog/KR                                         Version C-15
 (number . commands)
     Repeats  for  times.   If    is
     not positive, nothing is executed.
8.3.6. Editor Macros
Macro  commands  can  be  defined  using  the  full  power  of
Prolog/KR.   Following is an example definition of a predicate
to print every expression matching the pattern (given  as  the
        (EC:F *PAT) (EC:PP)
        (LOOP (IF (EC:FN) (EC:PP) (EXIT))))
In the  above  example,  (EC:PP)  is  repeated  until  (EC:FN)
finally fails.
The command defined above must be called as
To allow the user to call the command without parenthesis,
may be done.
 E:DEFCOM >command-name ›>calling-sequence®...
     Defines  to be as actually  calling  predi-
     cates as .
Some extra predicates are defined to support macros.
 E:SCOPE prompt .  If a  number  is
     read, the corresponding element in the stack is returned.
 E:GETFILE >filename filename >contents
     Dumps  to a file named .   
     must be a list of objects to be dumped.
Debugging Aids               -42-
Prolog/KR                                         Version C-15
9. Inputs and Outputs
9.1. Fundamental I/O Predicates
I/O  is  done  through  "streams"  whose  default  values  are
assigned  to  the terminal.  READ and PRINT interacts with the
terminal unless otherwise specified.   To  access  a  file,  a
stream  corresponding to the file must be created using INOPEN
or OUTOPEN according to whether the stream is input or  output
9.1.1. Inputs
 READ *result ›>stream®
     Reads one object from .  If  is  omitted,
     STANDARD-INPUT  is  assumed  (see  the  description about
     STANDARD-INPUT below).
     If  is not a variable, the read  object  is  com-
     pared  with  ;  if  they  do not match, then READ
     fails.  The read object will not be put back to the input
     stream  on  backtracking.   Nor no alternatives are read;
     READ simply fails on backtracking.  This feature  applies
     all the I/O predicates.
 RIND ›>prompt® *result
     Reads one object from the terminal prompting with  proper
     indentations.   This  is  also the way the top level loop
     reads.  Super parentheses, "›" and "®", are  also  avail-
     able in this mode.
     If  is a variable,  then  the  current  STANDARD-
     INPUT  is  returned.  If  is a input stream, then
     the STANDARD-INPUT is reset to .  A special  sym-
     bol TERMINAL-INPUT is recognized by this predicate: After
     is reset to the terminal.
          (STANDARD-INPUT )
     have almost the same effect except that  the  latter  may
     restore   the   previous  STANDARD-INPUT  after  (RETRACT
     STANDARD-INPUT)  but  the  former  does  not.   Asserting
     STANDARD-INPUT is recommended to be used with WITH as:
          (WITH ((STANDARD-INPUT (())))
              (do some inputs))
                             -43-           Inputs and Outputs
Prolog/KR                                         Version C-15
     which does not leave any change on STANDARD-INPUT.
 TERMINAL-INPUT object ›>stream® ›>printlevel®
     Prints    to    with  .   The
     default   values   of      and    are
     STANDARD-OUTPUT and 3 respectively.  Details of  
     whose  level  exceeds  is abbreviated to "?".
     If  is equal to or less than zero, no details
     are abbreviated.
 PRIN1 >object ›>stream® ›>printlevel®
     Just like PRINT except that  PRIN1  does  not  feed  line
     after  printing  .   Note  that  nothing  will be
     printed until TERPRI is executed.
 PRINC >object ›>stream® ›>printlevel®
     Just like PRIN1 except that PRINC does not supply """" or
     "/".   Note  that nothing will be printed until TERPRI is
 TERPRI ›>stream®
     Begins a new line.
 TAB >indentation ›>stream®
     Indent the output line to .  If the  current
     position is over the indentation, a new line with  is begun.
 GRIND >object
     "(GRIND object)" is equivalent  to  "(PRINT  object  0)".
     Note that GRIND always outputs to STANDARD-OUTPUT.
     Sets the default printlevel to .
 CASE *case
     If  is UPPER, then the outputs  are  printed  using
     upper-case  characters  (this is the default).  If 
     is LOWER, then  the  outputs  characters  are  lower-case
     ones.   These changes does not effect on printing strings
     (in strings, lower- and upper-cases are  preserved).   If
       is  a variable, either UPPER or LOWER is returned
     according to the status.  Note that CASE is used commonly
Inputs and Outputs           -44-
Prolog/KR                                         Version C-15
     by  all output streams (i.e., CASE is not the property of
     the stream).
     If  is an  integer,  then  the  line  size  of  the
     current output stream (STANDARD-OUTPUT) is set to .
     If  is a variable, then the current  line  size  is
     returned.  LINESIZE is a property of each stream.
     If  is a variable,  then  the  current  STANDARD-
     OUTPUT  is returned.  If  is a input stream, then
     the STANDARD-OUTPUT is reset to .  A special sym-
     bol  TERMINAL-OUTPUT  is  recognized  by  this predicate:
     After   doing   (STANDARD-OUTPUT   TERMINAL-OUTPUT)   the
     STANDARD-OUTPUT is reset to the terminal.
          (STANDARD-OUTPUT )
     have almost the same effect except that  the  latter  may
     restore   the  previous  STANDARD-OUTPUT  after  (RETRACT
     STANDARD-OUTPUT) but  the  former  does  not.   Asserting
     STANDARD-OUTPUT  is recommended to be used with WITH (see
     the description about STANDARD-INPUT above).
 TERMINAL-OUTPUT file-name .
       may  be  a  closed stream (a stream does not
     vanish away even it is closed).
 OUTOPEN >file-name .
       may  be  a  closed stream (a stream does not
     vanish away even it is closed).
 CLOSE >stream
     Closes  which has either been in-opened or  outo-
 NEW-FILE >file
     Creates a new file.   must be given as a string.
                             -45-           Inputs and Outputs
Prolog/KR                                         Version C-15
 LOAD >file
     Executes the contents of  and remembers  the  names
     of predicates defined in it.  The list which contains the
     contents of   is  called  "loaded-list".   "loaded-
     list" may be updated using ADD or DEL.
 LOADED >file *list
     Sets  to a list  of  predicate  names  loaded  from
       (called  "loaded-list").  Note that this does not
     return the original contents if "loaded-list" is modified
     by ADD or DEL.
 DUMP >file Ľ>definitionsļ
     Dumps  into .    must  be
     either  a  list  of  predicate  names or name of a world.
     Particularly, to dump all the definitions into a file,
     is useful.
     Something which is not a definition  of  a  predicate  --
     such  as  a  predicate  call of printing something -- can
     also be dumped by just adding it, instead of a  predicate
     name which is a symbol, into the list of predicate names.
     For example, after
     the contents of the file TEMP will be
         (PRINT BEGIN)
         (DEFINE P ... )
         (DEFINE Q ... )
         (PRINT END)
 STORE >file
     Restores definitions of predicates  loaded  from  .
     Addition  or deletion of those definitions to/from 
     is handled by the following two predicates.
     Note: STORE is recommended to be used  to  store  defini-
     tions  into an existing file.  DUMP is designed to create
     a new file and store definitions into it.
 ADD >file ›>predicate-name®...
     Adds s to the sets of  predicates  loaded
     from    ("loaded-list").   Note  that this does not
     change the actual contents of  until STORE is  exe-
 DEL >file ›>predicate-name®...
     Deletes s from  the  sets  of  predicates
     loaded  from  ("loaded-list").  Note that this does
     not change the actual contents of  until  STORE  is
Inputs and Outputs           -46-
Prolog/KR                                         Version C-15
10. Calling Lisp Functions
All the UTILISP functions can  be  called  from  Prolog/KR  by
   1) using a predicate X,
   2) giving one extra argument to receive the value,
   3) without the extra argument (those functions  are  listed
   later in this section).
Usually, Lisp functions are called directly; the last argument
is  supposed  to  be the value of the function.  For example a
Lisp function REVERSE is called as:
     (REVERSE (A B C) *X)
There are some Lisp functions values of which are  not  impor-
tant  (i.e.,  only  the  side effect is important).  There are
also some Lisp functions which are used as  predicates,  e.g.,
>,  <,  STRING-LESSP; in this case, the value is either T(rue)
or NIL(false).  Since the result is either  not  important  or
necessary  only  to control the behavior of the program, those
functions are called without extra arguments.  For those func-
tions,  the  call succeeds or fails according to the result is
non-nil or nil respectively.
Here is a list of Lisp functions to be  called  without  extra
 > >x ...
 < >x ...
 >= >x ...
 <= >x ...
 0> >x
 0< >x
 0= >x
 CALL >command ›>arguments®
 DEFCS >command-symbol >value
 GREATERP ›>x® ...
 LESSP ›>x® ...
 MEMQ >element >list
 STRING-LESSP >string1 >string2
 TYO >char ›>stream®
 VECTORP >object
Note: Arguments of the functions are not evaluated.  For exam-
     (CAR (CONS A B) *X)
                             -47-           Inputs and Outputs
Prolog/KR                                         Version C-15
instantiates *X to CONS, rather than A.
There is also a system defined predicate to  call  Lisp  func-
 X >function-name ›>argument®...
     Calls  with s.  s  are
Calling Lisp Functions       -48-
Prolog/KR                                         Version C-15
11. The Second Order Features
The second order features of  Prolog/KR  has  been  introduced
implicitly in the previous sections.  Those are:
   1) Arguments to a predicate themselves may be predicates.
   2) Predicate themselves may not have the fixed  interpreta-
   tions nor definitions; they are rather context dependent.
11.1. Variables as Predicates or Predicate Calls
User defined predicates  can  also  have  those  second  order
features  mentioned  above.   This  is done through variables;
variables may appear as predicates (the first element  of  the
predicate call) or as predicate calls.
Example: NOT may be defined as follows.
             (IF *PRED (FAIL)))
In the above example, the second appearance of "*PRED"  is  at
the place where a predicate call must be there.
Example: Here is an example in which a variable appears  as  a
predicate name.
     (ASSERT (MAP *FN (*A . *L) (*R . *REST))
             (*FN *A *R)
             (MAP *FN *L *REST))
11.2. Manipulating Programs as Data
In writing a compiler of Prolog in Prolog itself, for example,
a program must be treated as a datum.  In this case, variables
contained in the programs to be compiled should not be treated
as variables in pattern matching.  For example,
should not be called when compiling, say,
To avoid the matching between *N and NIL, either (a) the vari-
able  prefix should be changed so that *N is no longer a vari-
able, or (b) NIL should be quoted  as  'NIL  (cf.  3.1.1.)  to
avoid matching to variables.
Provided that the variable prefix is, for example, "=" in com-
piler,  all  the  usual  variables  such  as  "*X" or "*Y" are
treated as constants.  However, even if  the  variable  prefix
has  been  changed  to  avoid the problem, the compiler cannot
                             -49-    The Second Order Features
Prolog/KR                                         Version C-15
compile itself.  The latter solution (quoting) should be  used
in the compiler.
The Second Order Features    -50-
Prolog/KR                                         Version C-15
12. Miscellaneous Predicates
     Exits from Prolog/KR and returns to the OS level.
     Enters UTILISP top level.  (PGO)  transfers  the  control
     back to Prolog/KR.
 MEMBER *element >list
     Checks if  is a member of the .  If    is  an uninstantiated variable, elements of 
     are returned one by one on each backtracking.
 REWRITE >old-file >new-file
     Rewrites the contents of  which is  written  in
     the  old  syntax  (Prolog/KR I versions) to  in
     the new syntax.  The syntax of I versions is  very  close
     to that of Marseille Prolog.
     Enters the text editor TECO.  If the saved area for OS is
     too  small, calling TECO fails and exits Prolog/KR.  Just
     press the return key to come back to Prolog/KR then.
 TIME >predicate-call *time