File contents
<html>
<head>
<title>H. Nakashima. Prolog/KR manual</title>
</head>
<body>
<pre>
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
extremes.
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
letters.
Example: "PrettyPrint" may be spelled either "PP" or "PRETTY-
PRINT".
Meanings and functions of system defined predicates are
explained in the following form:
-1- Introduction
Prolog/KR Version C-15
<predicate name> <arguments>
........ <descriptions> ........
................................
<arguments> 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 <descriptions>. 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.
Examples:
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
arguments.
BAR >e1 *e2
BAR also takes two arguments. <e1> must be either a
variable which already has some value, or non-
variable object. That is, <e1> is an input argument
which expects to receive some value, rather than to
return a value.
<e2> may be anything, i.e., a variable or an object.
Example:
(BAR (A B) *X)
and
(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-
tion.
2.1. Variable
Variables are atoms (cf. 2.2.) which begin either with "*",
">" or "<", e.g.,
*X >X <Y * **THIS_IS_ALSO_A_VARIABLE**
where *X and >X are different variables.
Three kinds of prefixes are provided solely for readability.
The system does not distinguish those three kinds of vari-
ables.
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 <variable> has not been instantiated yet. If
<variable> has already been instantiated or is not a
variable at all, then it fails.
PREFIX >string ...
Changes the variable prefix to one of <string1>,
<string2>, ... Only the first characters in the strings
are effective.
Example:
(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
objects.
Examples:
(= (? ?) (A B)) succeeds
(= (* *) (A B)) fails
The anonymous variables are to be used where there is no
interest about the object.
Example:
(ASSERT (CAR (*CARPART . ?) *CARPART))
CAR is a predicate to return the first element of a list.
Since there is no interest about the rest of the list, "?" is
used.
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
characters:
" ", "(", ")", "", "", ";", "/", """", "'"
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 <x> 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:
(ASSERT (HUMAN TURING))
(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 <x> and <y> can be matched. If the matching
succeeds, variables in <x> and <y> 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 <x> and <y> are the same objects (in the sense
of Lisp's EQ). It does not suffice that they are the
same patterns.
Examples:
(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
equivalent.
Examples:
(= '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
FAIL:
(ASSERT (CAN PENGUIN WALK))
(ASSERT (CAN PENGUIN FLY) (FAIL))
(ASSERT (CAN HAWK FLY))
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:
(ASSERT (CAN 'PENGUIN 'FLY) (FALSE))
so that (CAN *X FLY) does not match (CAN 'PENGUIN 'FLY) but
(CAN HAWK FLY).
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
quotation:
(* 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:
(ASSERT (FACT *N
(! COND ((= *N 0) (= * 1))
((TRUE)
(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:
(ASSERT (FACT *N
(!a COND ((= *N 0) (= *a 1))
((TRUE)
(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 *)))
asserts
(P 2)
To prevent ! to be executed at the time of the assertion, it
must be quoted as:
(ASSERT (P '(! ADD1 1 *)))
Similarly,
(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)
results:
NIL
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)
LAST-INPUT *FORM
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)".
LAST-RESULT *RESULT
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.
TOP
Transfers the control to the top level loop.
PROLOG
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
one.
EPILOG
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.
Example:
:LIST FOO.VDATA(BAR)
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 <message> followed by <object>, where <message> is
a string and <object> 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.
Example:
(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"
"ILLEGAL FORM" "UNDEFINED PREDICATE" "UNDEFINED VARIABLE"
"ILLEGAL PATTERN" "NO MORE DATA AREA" "NO CATCHING STRUC-
TURE"
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-
tor.
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.
ATTENTION
STANDARD-ATTENTION-HANDLER
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,
use ASSERTA, ASSERTZ or EDIT.
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.
RETRACT >pat
If <pat> is a symbol, then all the assertions about <pat>
are retracted.
If <pat> 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))
or
(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 <name> to <definition-list>s.
-15- Predicate Definition
Prolog/KR Version C-15
The previous definition of <name> is overridden by the
new one.
<definition-list> is to be given in the following form:
(<arguments> . <body-list>)
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 <name> so that a predicate call
(name *X) returns <value>.
Example:
(SET X 1)
is equivalent to
(DEFINE X ((1)))
or
(RETRACT X)
(ASSERT (X 1))
DEFINITION >name *definition
Retrieves the definition of <name>. For example,
(DEFINE FALLIBLE ((*X) (HUMAN *X))
((*X) (GOD *X)))
(DEFINITION FALLIBLE *DEF)
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 <name> 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:
((<header1> . <body-list1>)
(<header2> . <body-list2>)
... )
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
as:
(DEFINE <name> . <definition-body>)
(DEFINITION <name> <definition-body>)
(WITH ((<name> . <definition-body>) ... ) ... )
-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
failure.
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.
FALSE
Always fails and triggers backtracking.
Example:
(AND (MEMBER *X (A B C))
(PRINT *X)
(FALSE))
produces a result:
A
B
C
NIL
where "NIL" indicates the failure of AND.
FAIL
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 <predicate>. There-
fore, NOT succeeds when <predicate> fails and fails when
<predicate> succeeds. Note that NOT do not instantiate
any variable because at least one failure occurs whether
in <predicate> or at NOT itself.
NOT is to be used only to test rather to return some
result.
(NOT (P *X))
means
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)))
succeeds.
TRUE
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,
<predicate-call> 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.
CUT
-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 <predicate-call>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)
(FALSE))
results:
B
C
Note that "(AND)" immediately succeeds.
OR >predicate-call...
Executes <predicate-call>s from left to right until one
of them succeeds. In case of later backtracking, the
alternatives of the <predicate-call> which succeeded most
recently are tried. If they all fail, the next
<predicate-call>, if any, is tried. If no <predicate-
call> remains, OR fails.
OR can be eliminated by providing extra predicate. For
example,
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 <predicate-call> succeeds, then <then-part> is exe-
cuted. Otherwise, <else-part> is executed; if <else-
part> is omitted, (TRUE) is assumed and IF succeeds.
Once <predicate> succeeds, it will not be backtracked
later, nor <else-part> will not be executed.
Example:
(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 <predicate-call>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
one.
Example: The result of
(DO (MEMBER *X (1 2 3))
(PRINT *X)
(FALSE)
(PRINT NEXT))
is
-21- Controls
Prolog/KR Version C-15
1
NEXT
(DO (MEMBER *X ?) (PRINT ?) ? . ?)
DAND >predicate-call...
Executes <predicate-call>s one by one until all of them
succeeds. If one of them fails, DAND fails without back-
tracking.
Example:
(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 <predicate-call>s one by one until one of them
succeeds. No alternatives are tried on later backtrack-
ing; DOR fails then.
Example:
(DOR a b c)
is equivalent to:
(IF a (TRUE)
(IF b (TRUE)
(IF c (TRUE) (FALSE))))
COND (>predicate . >body)...
Tries <predicate>s from left to right until one of them
succeeds, and then the corresponding <body> is executed.
Although backtracking may occur during the execution of
<body>, it does not propagate to <predicate> or other
alternatives; if <body> fails, then COND fails. Once
<body> succeeds COND succeeds and no more alternatives
are tried on later backtracking.
Example:
(COND ((AND (PRINT A) (FALSE)) (PRINT FIRST-CHOICE))
((PRINT B) (PRINT SECOND-CHOICE) (FALSE))
((PRINT THIS-WONT-BE-EXECUTED))) results:
A
B
SECOND-CHOICE
NIL
Controls -22-
Prolog/KR Version C-15
RETURN >predicate-call...
Fixes the choice of the alternatives of predicate to
<predicate-call>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
(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)
*P
(RETURN))
(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:
(RETURN (PRINT RETURNING-TWICE) (RETURN ...))
It may return or fail too many levels.
SELECT *pattern (*pattern1 . >body1) ...
Tries to match <pattern> to <pattern1>, <pattern2>, 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
as:
(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
as:
(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 <body>s for each alternative of <predicate-call>.
FOR-ALL succeeds if and only if
<predicate-call> logically implies <body>s.
In other words, FOR-ALL tests whether all solutions of
<predicate-call> also satisfy <body>. No variables are
instantiated inside FOR-ALL.
Example:
(AND (FOR-ALL (MEMBER *X (A B C)) (PRINT *X))
(VAR *X))
succeeds after printing:
A
B
C
Note that (VAR *X) succeeds, because *X is left uninstan-
tiated.
Controls -24-
Prolog/KR Version C-15
When <body>s fail, FOR-ALL immediately fails without try-
ing the next alternative of <predicate>. For example,
(FOR-ALL (MEMBER *X (A B C)) (PRINT *X) (FALSE))
results:
A
NIL
CANDIDATES *variable >predicate-call ...
Instantiates <variable> to a list of all the values of
<variable> which satisfies <predicate-call>s. <variable>
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
follows:
(ASSERT (INTERSECTION *X *Y *RESULT)
(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 <variable> to a list of <structure> the
value of which is determined by each alternative of
<predicate>. 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.
(ASSERT (INTERSECTION *X *Y *RESULT)
(ACCUMULATE *TEMP
(AND (MEMBER *TEMP *X)
-25- Controls
Prolog/KR Version C-15
(MEMBER *TEMP *Y))
*RESULT))
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 <predicate-call>s until EXIT is executed.
"while-do" and "repeat-until" are considered to be spe-
cial cases of LOOP.
Examples:
(ASSERT (WHILE-DO *P *BODY)
(LOOP (IF *P (TRUE) (EXIT)) *BODY))
(ASSERT (REPEAT-UNTIL *BODY *P)
(LOOP *BODY (IF *P (EXIT))))
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 <predicate-call>s in a pseudo parallel mode.
Usually, each <predicate-call> is executed one step (one
predicate invocation) and then another one is executed.
As the name suggests, there is no interaction between
<predicate-call>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 <predicate-call>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 <predicate-call>s are executed. For
example,
(AND (POR (AND (PRINT A) (PRINT B))
(OR (PRINT OR-1) (PRINT OR-2))
(PRINT C))
(FALSE))
results:
A
Controls -26-
Prolog/KR Version C-15
OR-1
NIL
Note that the same rule is applied when POR is called
within POR.
6.6. Non Local Exit
CATCH >predicate-call
Executes <predicate-call>. If THROW is executed during
the execution of <predicate-call>, the control may return
to CATCH if the following conditions are satisfied:
1) <predicate-call> matches the argument of the THROW.
2) The CATCH is the inner-most one which satisfies 1).
In this case, variables in <predicate-call> are instan-
tiated through the pattern matching.
If <predicate-call> 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 <pattern>.
Example: Here is a definition of DOR using CATCH and
THROW.
(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 <predicate-call> and name the
producer uniquely. The unique name is returned to
<name>.
Example:
-27- Controls
Prolog/KR Version C-15
(INITIATE (MEMBER *X (A B C)) *M)
NEXT >producer . >pattern
Gets one result from <producer>. 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 <pattern>.
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))
or
(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, <pattern> 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 <pattern> into the internal data base. <pattern>
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
backtracking.
RECORDED >pattern
Retrieves one element in the internal data base which
matches <pattern>. 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 <pattern> is RECORDed. The daemon vanishes after
one activation.
Example:
(RECORDING (HUMAN TURING)
(PRINC "Turing is a human.")
(TERPRI)
(RECORD (FALLIBLE TURING)))
(RECORDING (FALLIBLE TURING)
(PRINC "Turing is fallible."))
(RECORD (HUMAN TURING))
results:
Turing is a human.
Turing is fallible.
If there already exists a datum which matches <pattern>,
the daemon is immediately activated.
ERASE >pattern
-29- Data Base Facilities
Prolog/KR Version C-15
Erases one datum which matches <pattern>. 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
as:
(WITH name-of-the-world (predicate .... ))
The following picture gives a rough idea of relations between
worlds.
------------- -----------
| WORLD-A | | WORLD-A |
------------------ ---------------
| STANDARD-WORLD | | WORLD-B |
----------------------------------------------
| WORLD-OF-SYSTEM-DEFINED-PREDICATES
------------------------------------------------------
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
systems.
WITH >world >body...
If <world> is a name of a world (i.e., a symbol), then
WITH executes <body>s within the world. If the name of
the world is a new one, then a new world is created.
If <world> is a list of predicate definitions, then those
definitions become visible only while <body>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 <world>.
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 <name>, which initially con-
tains predicate definitions given by <predicate-
definition>s.
Example:
(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/ -))
prints
- A -
while both
(PRINT /-/ A/ -)
and
(GRIND /-/ A/ -)
print
/-/ A/ -
ERASE-WORLD >name
Destroys the world <name> so that it no more contains
definitions.
LOAD-WORLD >file-name >name
Loads definitions from <file-name> into a world <name>.
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
WORLD-NAME *name
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 <mode>: if <mode> is
ON, then the interpreter runs in debugging mode
thereafter; if <mode> is OFF, then the interpreter runs
in non-debugging mode; if <mode> is a variable, then the
current mode (ON or OFF) is returned.
BACKTRACE *list
Returns the history of the execution (including back-
tracking) to <list>.
8.1. Tracer
TRACE >name...
Enables tracing of <name>s. The output of the tracer is
in the following form:
level (predicate-call)
or
level= (predicate-call)
The former is printed when a predicate call is tried; the
latter is printed when it succeeds.
TRACE-ALL
Enables tracing of all predicates.
UNTRACE >name...
Disables tracing of <name>s.
UNTRACE-ALL
Disables tracing of all predicates.
8.2. Stepper
The stepper is called via STEP.
STEP >predicate-call >name...
Execute <predicate-call> in a step-by-step manner. On
each step, the stepper requests for command(s) to deter-
mine the next action.
If <name>s are supplied, the stepper stops only at the
entrances of <name>s.
The stepper commands are:
C
-33- Debugging Aids
Prolog/KR Version C-15
Continue step-by-step execution.
F
Finish step-by-step mode and resume normal execution.
G
Execute the body in normal mode and return to step-by-
step mode afterwards.
Q
Quit stepping and return to the top level.
BackTrace
Backtrace the history of the execution. BT prints the
outlines, while BACKTRACE prints with details. Debug
mode must be on to use this command.
PP
Prettyprint the current goal.
list
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)
or
(EDIT "file-name")
respectively.
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 <name>. If <name> is a symbol, the definition of
<name> is edited. If <name> 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.
Example:
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)
(X)
(&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)))
to
(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:
(EDIT FOO (PP 1 I (SOMETHING)))
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:
B
(EC:B)
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 <number1>th to <number2>th) in
parentheses.
Example:
BI 2 3
changes
(A B C D E F G)
to
(A (B C) D E F G)
BO
(EC:BO)
Removes the parentheses enclosing the current scope (the
opposite of BI).
C
(EC:C)
Copies the current scope to the top of the stack.
D
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
level.
E name
(EC:E name)
Abandons the result of the current editing and shift the
object of editing to <name>.
F pattern
(EC:F pattern)
Moves to an element which matches <pattern>. 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.
FN
(EC:FN)
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 <element> just after the current element. The
scope is shifted to the inserted element.
IB element
(EC:IB element)
Inserts <element> just before the current element. The
scope is not changed.
K
(EC:K)
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.
L
(EC:L)
Moves to the last element of the current scope.
LD
(EC:LD)
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
LI
(EC:LI)
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 <number>. The default depth
is 7.
N
(EC:N)
Moves to the next element. If the current element is the
last one, then an error is issued.
P
(EC:P)
Prints the current element without details. Details are
printed by "?". The level of the printing is controlled
by LEVEL.
PP
(EC:PP)
Prints the current element with details.
POP
O
(EC:POP)
Pops the stack.
Q
(EC:Q)
Restores the result of the editing and exits from the
editor.
R element
(EC:R element)
Replaces the current scope by <element>.
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 <pattern1> by <pattern2>.
<pattern1> is matched with the element on each replace-
ment. Hence, variables appearing in <pattern2> are
replaced properly. The scope is not changed by the com-
mand.
-39- Debugging Aids
Prolog/KR Version C-15
If <maximum-number-of-replacement> is supplied, then only
the first <maximum-number-of-replacement> patterns are
replaced.
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.
RI
(EC:RI)
Inserts a right parenthesis just after the current scope.
Example: If the current scope is
(A $$$ C)
RI changes it to:
((A $$$) C)
S
(EC:S)
Restores the current result without exiting from the edi-
tor.
SC name
(EC:SC name)
Stores the current result of editing to <name>. When a
file is being edited, <name> must be a name of an exist-
ing file, expressed as a string.
STACK
(EC:STACK)
ST
(EC:ST)
Prints the contents of the stack.
TOP
(EC:TOP)
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 <symbol>. For example,
U DEFINE
Debugging Aids -40-
Prolog/KR Version C-15
goes up to a structure (DEFINE ...).
V
(EC:V)
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 <character>. The original
variable prefix is "&".
X predicate-call
(EC:X predicate-call)
Executes <predicate-call> and prints the result. Like
other commands, elements in the stack can be given as
<predicate-call> 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".
Z
(EC:Z)
Abandons editing and exit. The original definition or
contents of the file are not changed.
?
(EC:?)
Prints the name of the predicate/file which is being
edited.
number
(E:MOVE number)
Moves to the <number>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.
Example:
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
L
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
Prolog/KR.
-41- Debugging Aids
Prolog/KR Version C-15
(number . commands)
Repeats <commands> for <number> times. If <number> 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
argument).
(ASSERT (PRINT-ALL *PAT)
(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
(PRINT-ALL)
To allow the user to call the command without parenthesis,
(E:DEFCOM PRINT-ALL (PRINT-ALL))
may be done.
E:DEFCOM >command-name >calling-sequence...
Defines <command-name> to be as actually calling predi-
cates as <calling-sequence>.
Some extra predicates are defined to support macros.
E:SCOPE <scope
Returns the current scope.
E:STACK <stack
Returns a list of all the contents of the stack.
E:READ >prompt <object
Gets one argument with prompt <prompt>. If a number is
read, the corresponding element in the stack is returned.
E:GETFILE >filename <contents
Reads the contents of the file and returns a list of
them.
E:PUTFILE >filename >contents
Dumps <contents> to a file named <filename>. <contents>
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
respectively.
9.1.1. Inputs
READ *result >stream
Reads one object from <stream>. If <stream> is omitted,
STANDARD-INPUT is assumed (see the description about
STANDARD-INPUT below).
If <result> is not a variable, the read object is com-
pared with <result>; 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.
STANDARD-INPUT *stream
If <stream> is a variable, then the current STANDARD-
INPUT is returned. If <stream> is a input stream, then
the STANDARD-INPUT is reset to <stream>. A special sym-
bol TERMINAL-INPUT is recognized by this predicate: After
doing (STANDARD-INPUT TERMINAL-INPUT) the STANDARD-INPUT
is reset to the terminal.
You may also ASSERT or DEFINE STANDARD-INPUT:
(STANDARD-INPUT <stream>)
and
(ASSERT (STANDARD-INPUT <stream>))
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 ((<stream>))))
(do some inputs))
-43- Inputs and Outputs
Prolog/KR Version C-15
which does not leave any change on STANDARD-INPUT.
TERMINAL-INPUT <stream
Returns a input stream which is connected to your termi-
nal. Note that this predicate is output only, unlike
STANDARD-INPUT.
PROMPT <character
Returns the default prompt character. To change the
default prompt character, you must redefine PROMPT (by
either ASSERT, DEFINE or WITH).
9.1.2. Outputs
PRINT >object >stream >printlevel
Prints <object> to <stream> with <printlevel>. The
default values of <stream> and <printlevel> are
STANDARD-OUTPUT and 3 respectively. Details of <object>
whose level exceeds <printlevel> is abbreviated to "?".
If <printlevel> 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 <object>. 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
executed.
TERPRI >stream
Begins a new line.
TAB >indentation >stream
Indent the output line to <indentation>. If the current
position is over the indentation, a new line with <inden-
tation> is begun.
GRIND >object
"(GRIND object)" is equivalent to "(PRINT object 0)".
Note that GRIND always outputs to STANDARD-OUTPUT.
PRINT-LEVEL >level
Sets the default printlevel to <level>.
CASE *case
If <case> is UPPER, then the outputs are printed using
upper-case characters (this is the default). If <case>
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
<case> 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).
LINESIZE *size
If <size> is an integer, then the line size of the
current output stream (STANDARD-OUTPUT) is set to <size>.
If <size> is a variable, then the current line size is
returned. LINESIZE is a property of each stream.
STANDARD-OUTPUT *stream
If <stream> is a variable, then the current STANDARD-
OUTPUT is returned. If <stream> is a input stream, then
the STANDARD-OUTPUT is reset to <stream>. 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.
You may also ASSERT or DEFINE STANDARD-OUTPUT:
(STANDARD-OUTPUT <stream>)
and
(ASSERT (STANDARD-OUTPUT <stream>))
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 <stream
Returns a input stream which is connected to your termi-
nal. Note that this predicate is output only, unlike
STANDARD-OUTPUT.
9.2. File Manipulations
INOPEN >file-name <stream
Creates an input stream by opening a file <file-name>.
<file-name> may be a closed stream (a stream does not
vanish away even it is closed).
OUTOPEN >file-name <stream
Creates an output stream by opening a file <file-name>.
<file-name> may be a closed stream (a stream does not
vanish away even it is closed).
CLOSE >stream
Closes <stream> which has either been in-opened or outo-
pened.
NEW-FILE >file
Creates a new file. <file> must be given as a string.
-45- Inputs and Outputs
Prolog/KR Version C-15
LOAD >file
Executes the contents of <file> and remembers the names
of predicates defined in it. The list which contains the
contents of <file> is called "loaded-list". "loaded-
list" may be updated using ADD or DEL.
LOADED >file *list
Sets <list> to a list of predicate names loaded from
<file> (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 <definitions> into <file>. <definitions> must be
either a list of predicate names or name of a world.
Particularly, to dump all the definitions into a file,
(DUMP <file-name> STANDARD-WORD)
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
(DUMP "TEMP" ((PRINT BEGIN) P Q (PRINT END)))
the contents of the file TEMP will be
(PRINT BEGIN)
(DEFINE P ... )
(DEFINE Q ... )
(PRINT END)
STORE >file
Restores definitions of predicates loaded from <file>.
Addition or deletion of those definitions to/from <file>
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 <predicate-name>s to the sets of predicates loaded
from <file> ("loaded-list"). Note that this does not
change the actual contents of <file> until STORE is exe-
cuted.
DEL >file >predicate-name...
Deletes <predicate-name>s from the sets of predicates
loaded from <file> ("loaded-list"). Note that this does
not change the actual contents of <file> until STORE is
executed.
Inputs and Outputs -46-
Prolog/KR Version C-15
10. Calling Lisp Functions
All the UTILISP functions can be called from Prolog/KR by
either:
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
arguments:
> >x ...
< >x ...
>= >x ...
<= >x ...
0> >x
0< >x
0= >x
CALL >command >arguments
DEFCS >command-symbol >value
GREATERP >x ...
LISTP >x
LESSP >x ...
MEMQ >element >list
NUMBERP >x
STRING-LESSP >string1 >string2
STRINGP >x
TYO >char >stream
VECTORP >object
ZEROP >x
Note: Arguments of the functions are not evaluated. For exam-
ple:
(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-
tions.
X >function-name >argument...
Calls <function-name> with <argument>s. <Argument>s are
evaluated.
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.
(ASSERT (NOT *PRED)
(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,
(ASSERT (COMPILE (*FUNCTION NIL)) ... )
should not be called when compiling, say,
(FACTORIAL *N)
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
QUIT
END
EPILOG
Exits from Prolog/KR and returns to the OS level.
LISP
Enters UTILISP top level. (PGO) transfers the control
back to Prolog/KR.
MEMBER *element >list
Checks if <element> is a member of the <list>. If <ele-
ment> is an uninstantiated variable, elements of <list>
are returned one by one on each backtracking.
REWRITE >old-file >new-file
Rewrites the contents of <old-file> which is written in
the old syntax (Prolog/KR I versions) to <new-file> in
the new syntax. The syntax of I versions is very close
to that of Marseille Prolog.
TECO
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
Sets <time> to the CPU time (in milliseconds) elapsed in
executing <predicate-call>.
VERSION
Prints the current version name.
HELP >predicate-name
Prints the contents of this manual about <predicate-
name>. The printing out continues as far as 20 lines and
"--more--" is printed waiting for your input. Simply
pressing the return key continues the output (for more 20
lines). Any character followed by the return key or a
single bleak (without any preceding characters) stops the
output.
Note: any characters after (HELP ...) on the same line
are ignored.
MANUAL >output
Prints this manual. If <output> is omitted, the output
is your terminal. If <output> is supplied, the output is
changed according to <output>:
number
The output is your terminal. But the ptinting pauses
every <output> lines. Hit the return key to continue.
Hit break to quit. This is convenient to be used from
display terminals.
-51- Miscellaneous Predicates
Prolog/KR Version C-15
file-name
The output is the file. The file must exist (to create a
file, use NEW-FILE).
LP The output is the line printer. Use a line printer which
has lower case letters for printing.
Miscellaneous Predicates -52-
Prolog/KR Version C-15
Appendix A. How to Enter Prolog/KR
There are basically two ways to invoke Prolog/KR:
(1) Call the function PROLOG in Utilisp.
>> UTILISP FIX(40)
> (PROLOG)
(2) Use the command procedure PROLOG.
>> PROLOG
There are several optional parameters to PROLOG.
SAVE(pages) : Area size in pages (one page is 4KB) to be
saved for the operating system. This area is not
required unless you call the OS commands from inside
Prolog/KR. The default value is 32.
STACK(pages) : Area size in pages for the system stack.
The default value is 16.
INITIAL(file-name) : A file name the contents of which
are to be executed before reading from the terminal.
HELP : If this option is given, a brief survey of the
options are printed instead of invoking Prolog/KR.
Example:
>> PROLOG SAVE(0) INITIAL(ANTI.PKR)
may invoke your own system ANTI written in Prolog/KR.
If you assign a command symbol PROLOGLIB to an existing file,
>> SETCS PROLOGLIB file.name
then the contents of the file is executed first of all (even
before executing the file given as INITIAL parameter). PROLO-
GLIB is supposed to be linked to a file which contains your
own definitions of utility predicates.
How to Enter Prolog/KR A-1 Appendix
Prolog/KR Version C-15
Appendix B. Examples
Definitions of control predicates are given in Prolog/KR
itself to help users understand the language. Since some con-
trol predicates are impossible to give their definitions, only
those which can be defined in terms of other predicates are
listed. Note that these definitions have nothing to do with
the actual implementation.
(ASSERT (AND >PRED . >REST) >PRED (AND >REST))
(ASSERT (AND))
(ASSERT (COND (>PRED . >BODY) . >REST)
(IF >PRED >BODY (COND . >REST)))
(ASSERT (DOR >PRED . >REST)
(IF >PRED (TRUE) (DOR . >REST)))
(ASSERT (FALSE) (FAIL 0))
(ASSERT (IF >PRED >THEN . >ELSE)
>PRED (RETURN >THEN))
(ASSERT (IF >PRED >THEN . >ELSE)
(RETURN . >ELSE))
(ASSERT (NOT >PRED) (IF >PRED (FAIL)))
(ASSERT (OR >PRED . >REST) >PRED)
(ASSERT (OR >PRED . >REST) (OR . >REST))
Following is a definition of map which maps a predicate over
lists of arguments. For example:
(MAP APPEND ((A B) (C D))
((0 1) (2 3 4))
((A B 0 1) (C D 2 3 4)))
holds.
(ASSERT (NILS NIL))
(ASSERT (NILS NIL . *NILS) (NILS *NILS))
(ASSERT (DIVIDE NIL NIL NIL)
(ASSERT (DIVIDE ((*CAR . *CDR) . *REST)
(*CAR . *CARS) (*CDR . *CDRS))
(DIVIDE *REST *CARS *CDRS))
(ASSERT (MAP *FN . *ARGS)
(DIVIDE *ARGS *CARS *CDRS) (*FN . *CARS)
(RETURN (MAP *FN . *CDRS)))
(ASSERT (MAP *FN . *ARGS) (NILS *ARGS))
(ASSERT (CARS NIL NIL))
(ASSERT (CARS ((*CAR . *CDR) . *REST) (*CAR . *RESULT))
(CARS *REST *RESULT)))
(ASSERT (CDRS NIL NIL))
(ASSERT (CDRS ((*CAR) . *REST) *Y) (FAIL))
(ASSERT (CDRS ((*CAR . *CDR) . *REST) (*CDR . *RESULT))
(CDRS *REST *RESULT))
Examples B-1 Appendix
Prolog/KR Version C-15
There follows a definition of FOR which iterates the body,
just like other conventional languages,
giving a variable consecutive values from <FROM> to <TO>.
(ASSERT (FOR *I *FROM *TO . *BODY)
(WITH ((:FOR-INDEX))
(DO (*I *FROM (! ADD1 (! :FOR-INDEX *) *))
(<= *I *TO)
(SET :FOR-INDEX *I)
(AND . *BODY
Examples B-2 Appendix
</pre>
</body>
</html>