CLIPS User Guide
CLIPS User Guide
Chapter 1
Chapter 2
Chapter 3
Adding Details
Chapter 4
Variable Interests
Chapter 5
Doing It Up In Style
Chapter 6
Being Functional
Chapter 7
How to Be in Control
Chapter 8
Matters of Inheritance
Chapter 9
Meaningless Messages
Chapter 10
Fascinating Facets
Chapter 11
Handling Handlers
Chapter 12
This section was formerly called the Preface, but since nobody read it, I renamed it to
a more conventional title that computers users are conditioned to obey. Another
suggestion was to call this the Don't Readme section, but since people today believe
everything they read, I was afraid they really wouldn't read it.
What Is CLIPS?
CLIPS is an expert system tool developed by the Software Technology Branch (STB),
NASA/Lyndon B. Johnson Space Center. Since its first release in 1986, CLIPS has
undergone continual refinement and improvement. It is now used by thousands of
people around the world. The Internet news group comp.ai.shells often has
discussions of CLIPS. NASA supports CLIPS and other software products developed
by the STB through the STB Bulletin Board (please see back of this book for more
details.)
_ Rules, which are primarily intended for heuristic knowledge based on experience.
_ Deffunctions and generic functions, which are primarily intended for procedural
knowledge.
You can develop software using only rules, only objects, or a mixture of objects and
rules.
CLIPS has also been designed for full integration with other languages such as C and
Ada. In fact, CLIPS is an acronym for C Language Integrated Production System.
Rules and objects form an integrated system too since rules can pattern-match on facts
and objects. In addition to being used as a stand-alone tool, CLIPS can be called from
a procedural language, perform its function, and then return control back to the calling
program. Likewise, procedural code can be defined as external functions and called
from CLIPS. When the external code completes execution, control returns to CLIPS.
If you are already familiar with object-oriented programming in other languages such
as C++, Smalltalk, Object C, or Turbo Pascal, you know the advantages of objects in
developing software. If you are not familiar with object-oriented programming, you
will find that CLIPS is an excellent tool for learning this new concept in software
development.
The CLIPS User's Guide is an introductory tutorial on the basic features of CLIPS. It
is not intended to be a comprehensive discussion of the entire tool. The companion
volume to this book is theCLIPS Reference Manual., which does provide a complete,
comprehensive discussion of all the topics in this book and much more.
The purpose of the CLIPS User's Guide is to provide an easy to read, elementary
introduction to expert systems for people with little or no experience with expert sys
tems.
The CLIPS User's Guide can be used in the classroom or for self-teaching. The only
prerequisite is that you have a basic knowledge of programming in a high-level
language such as Pascal, Ada, FORTRAN, C (OK, BASIC if nothing else, but we
won't admit it in public and will disavow this statement if asked.)
The CLIPS User's Guide is designed for people who want a quick introduction to
expert system programming in a hands-on manner. The examples are of a very general
nature. Also, since learning a new language can be a frustrating experience, the
writing is in a light, humorous style (I hope) compared to serious-minded, massive,
and intimidating college textbooks. Hopefully, the humor will not offend anyone with
a sense of humor.
For maximum benefit, you should type in the example programs in the text as you
read through the book. By typing in the examples, you will see how the programs
should work and what error messages occur if you make a mistake. The output for the
examples is shown or described after each example. Finally, you should read the
corresponding material in the CLIPS Reference Manual as you cover each chapter in
the CLIPS User's Guide..
Like any other programming language, you will only learn programming in CLIPS by
writing programs in it. To really learn expert system programming, you should pick a
problem of interest and write it in CLIPS.
Acknowledgments
I greatly appreciate the advice and reviews of this book by many people. Thanks to
Gary Riley, Chris Culbert, Brian Donnell, Bryan Dulock, Steven Lewis, Ann Baker,
Steve Mueller, Stephen Baudendistel, Yen Huynh, Ted Leibfried, Robert Allen, Jim
Wescott, Marsha Renals, Pratibha Boloor, Terry Feagin, and Jack Aldridge. Special
thanks to Bob Savely for supporting the development of CLIPS.
Chapter 1 Just the Facts
If you ignore the facts, you'll never worry about being wrong
This chapter introduces the basic concepts of an expert system. You'll see how to
insert and remove facts in CLIPS. If you are using a Macintosh or the Windows
version of CLIPS for the IBM PC (or compatible), you can select most commands by
the mouse instead of typing them in. The arrow keys on the keyboard will also move
the cursor and allow selection of menu items.
Introduction
CLIPS is a type of computer language designed for writing applications called expert
systems. An expert system is a program which is specifically intended to model
human expertise or knowledge. In contrast, common programs such as payroll
programs, word processors, spreadsheets, computer games, and so forth, are not
intended to embody human expertise or knowledge. (One definition of an expert is
someone more than 50 miles from home and carrying a briefcase.)
A program written in CLIPS may consist of rules, facts, and objects. The inference
engine decides which rules should be executed and when. A rule- based expert system
written in CLIPS is a data-driven program where the facts, and objects if desired, are
the data that stimulate execution via the inference engine.
This is one example of how CLIPS differs from procedural languages such as Pascal,
Ada, BASIC, FORTRAN, and C. In procedural languages, execution can proceed
without data. That is, the statements are sufficient in those languages to cause
execution. For example, a statement such as PRINT 2 + 2 could be immediately
executed in BASIC. This is a complete statement that does not require any additional
data to cause its execution. However, in CLIPS, data are required to cause the
execution of rules.
Originally, CLIPS had capabilities to represent only rules and facts. However, the
enhancements of Version 6.0 allow rules to match objects as well as facts. Also,
objects may be used without rules by sending messages and so the inference engine is
no longer necessary if you use only objects. In chapters 1 through 7, we'll discuss the
facts and rules of CLIPS. The object features of CLIPS are covered in chapters 8
through 12.
To begin CLIPS, just enter the appropriate run command for your system. You should
see the CLIPS prompt appear as follows:
CLIPS>
At this point, you can start entering commands directly into CLIPS. The mode in
which you are entering direct commands is called the top-level. If you have a window
version of CLIPS, you can just select the command using the mouse or arrow keys
rather than typing it in. Please refer to the CLIPS Reference Manual for a discussion
of the commands supported under windows. For simplicity and uniformity in this
book, we'll assume the commands are typed in.
The normal mode of leaving CLIPS is with the exit command. Just type
(exit)
in response to the CLIPS prompt and then press the carriage return key.
Making a List
As an example of assert, enter the following right after the CLIPS prompt as shown:
CLIPS> (assert (duck))
Here the assert command takes (duck) as its argument. Be sure to always press the
carriage return key to send the line to CLIPS.
which indicates CLIPS has stored the duck fact in the fact-list and given it the
identifier 0. The angle-brackets are used as a delimiter in CLIPS to surround the name
of an item. CLIPS will automatically name facts using a sequentially increasing
number and list the highest fact-index when one or more facts is asserted.
Notice that the (assert) command and its (duck) argument are surrounded by
parentheses. Like many other expert system languages, CLIPS has a LISP-like syntax
which uses parentheses as delimiters. Although CLIPS is not written in LISP, the style
of LISP has influenced the development of CLIPS.
Suppose you want to see what's in the fact-list. If your version of CLIPS supports
windows, you may just select the appropriate command from the menu. Alternatively,
you can enter commands from the keyboard. In the following, we'll describe the
keyboard commands since the window selections are self-explanatory.
The keyboard command to see facts is with the facts command. Enter (facts) in
response to the CLIPS prompt and CLIPS will respond with a list of facts in the fact-
list. Be sure to put parentheses around the command or CLIPS will not accept it. The
result of the (facts) command in this example should be
CLIPS> (facts)
f-0 (duck)
CLIPS>
The term f-0 is the fact identifier assigned to the fact by CLIPS. Every fact inserted
into the fact-list is assigned a unique fact identifier starting with the letter "f" and
followed by an integer called the fact-index. On starting up CLIPS, and after certain
commands such as clear and reset (to be discussed in more detail later), the fact-index
will be set to zero, and then incremented by one as each new fact is asserted. The
(reset) command will also insert a fact (initial-fact) as f-0. This fact is often used for
convenience to initially activate rules. Shown following is what happens when a
(reset) is done first.
CLIPS> (reset)
<Fact-1>
CLIPS> (facts)
f-0 (initial-fact)
f-1 (duck)
CLIPS>
Notice that the fact-index is <Fact-1> after the duck fact is asserted because there are
now two facts in working memory and the duck has index 1.
What happens if you try to put a second duck into the fact-list? Let's try it and see.
Assert a new (duck), then issue a (facts) command as follows
CLIPS> (assert (duck))
FALSE
CLIPS> (facts)
f-0 (initial-fact)
f-1 (duck)
CLIPS>
The FALSE message is returned by CLIPS to indicate that it was not possible to
perform this command. You'll see just the original "f-1 (duck)". This shows that
CLIPS will not accept a duplicate entry of a fact. However, there is an override
command, setfact-duplication, which will allow duplicate fact entry.
Of course you can put in other, different facts. For example, assert a (quack) fact and
then issue a (facts) command. You'll see
CLIPS> (assert (quack))
<Fact-2>
CLIPS> (facts)
f-0 (initial-fact)
f-1 (duck)
f-2 (quack)
CLIPS>
Facts may be removed or retracted. When a fact is retracted, the other facts do not
have their indices changed, and so there may be "missing" fact-indices. As an
analogy, when a football player leaves a team and is not replaced, the jersey numbers
of the other players are not all adjusted because of the missing number (unless they
really hate the guy's guts and want to forget he ever played for them.)
The clear command removes all facts from memory, as shown by the following.
CLIPS> (facts)
f-0 (initial-fact)
f-1 (duck)
f-2 (quack)
CLIPS> (clear)
CLIPS>
The (clear) command essentially restores CLIPS to its original startup state. It clears
the memory of CLIPS and resets the fact-identifier to zero. To see this, assert (animal-
is duck), then check the fact-list. Notice that (animal-is duck) has a fact-identifier of f-
0 because the (clear) command reset the fact identifiers. The (clear) command actually
does more than just remove facts. Besides removing all the facts, (clear) also removes
all the rules, as you'll see in the next chapter.
The following example shows how three facts are asserted, and the (facts) command
is used. The (clear) command is used to get rid of all facts in memory and reset the
fact-indices to start with f-0.
CLIPS> (clear)
<Fact-2>
CLIPS> (facts)
f-0 (a)
f-1 (b)
f-2 (c)
CLIPS> (facts 0)
f-0 (a)
f-1 (b)
f-2 (c)
CLIPS> (facts 1)
f-1 (b)
f-2 (c)
CLIPS> (facts 2)
f-2 (c)
CLIPS> (facts 0 1)
f-0 (a)
f-1 (b)
CLIPS> (facts 0 2 2)
f-0 (a)
f-1 (b)
CLIPS>
Notice only one (assert) is used to assert the three facts, (a), (b), and (c). The highest
fact-index is 2 and this is returned by CLIPS in the informational message <Fact- 2>.
The much longer alternative would be to assert one fact per command (This may be
done by people who like to show off their typing speed.)
The (duck) fact has a single, unnamed placeholder for the value duck. This is an
example of a single-field fact. A field is a placeholer for a value. As an analogy to
fields, think of dishes (fields) for holding food (values).
The order of unnamed fields is significant. For example, if a fact was defined
(Brian duck)
and interpreted by a rule as the hunter Brian shot a duck, then the fact
(duck Brian)
would mean that the hunter duck shot a Brian. In contrast, the order of named fields is
not significant, as you'll see later with deftemplate.
Actually, it is good software engineering to start the fact with a relation that describes
the fields. A better fact would be
to imply that the first field is the hunter and the second field is the game.
A few definitions are now necessary. A list is a group of items with no implied order.
Saying that a list is ordered means that the position in the list is significant. A
multifield is a sequence of fields, each of which may have a value. The examples of
(duck Brian) and (Brian duck) are multifield facts. If a field has no value, the special
symbol nil, which means "nothing" may be used for an empty field as a placeholder.
For example,
(duck nil)
Note that the nil is necessary to indicate a placeholder, even if it has no value. For
example, think of a field as analogous to a mailbox. There's a big difference between
an empty mailbox, and no mailbox at all. Without the nil, the fact becomes a single-
field fact (duck). If a rule depends on two fields, it will not work with only one field,
as you'll see later.
There are a number of different types of fields available: float, integer, symbol, string,
externaladdress, factaddress, instancename and instanceaddress The type of each field
is determined by the type of value stored in the field. In an unnamed field, the type is
determined implicitly by what type you put in the field. In deftemplates, you
can explicitlty declare the type of value that a field can contain. The use of explicit
types enforces the concepts of software engineering, which is a discipline of
programming to produce quality software.
A symbol is one type of field that starts with a printable ASCII character and is
followed optionally by zero or more printable characters. Fields are commonly
delimited or bounded, by one or more spaces or parentheses. For example,
(duck-shot Brian Gary Rey)
has four fields to indicate all the hunters shot by the killer duck. In this fact, the fields
are delimited by spaces, and the opening and closing parentheses.
Facts are not allowed to be embedded within other facts. For example, the following is
an illegal ordered fact.
(duck (shot Brian Gary Rey))
However, this could be a legal defte mplate fact if "shot" is defined as the name of a
field, while "Brian Gary Rey" are the values associated with the named field.
The "&", "|", and "~" may not be used as stand-alone symbols or as any part of a
symbol.
Some characters act as delimiters by ending a symbol. The following characters act as
delimiters for symbols.
_ any non-printable ASCII character, including spaces, carriage returns, tabs, and
linefeeds
_ ampersand, &
_ vertical bar, |
_ less than, <. Note that this may be the first character of a symbol
_ tilde, ~
The semicolon acts as the start of a comment in CLIPS. If you try to assert a
semicolon, CLIPS will think you're entering a comment and wait for you to finish. If
you accidentally enter a semicolon in top-level, just type in a closing parenthesis and
carriage return. CLIPS will respond with an error message and the CLIPS prompt will
reappear (This is one of the few approved occasions in life in which it's necessary to
do something wrong to get something right.)
As you read through this manual, you will learn the special meanings of the characters
above. With the exception of the "&", "|", and "~", you may use the others as
described. However, it may be confusing to someone reading your program and trying
to understand what the program is doing. In general, it's best to avoid using these
characters in symbols unless you have some good reason for using them.
duck1
duck_soup
duck-soup
duck1-1_soup-soup
d!?#%^
The second type of field is the string. A string must begin and end with double quotes.
The double quotes are part of the field. Zero or more characters of any kind can
appear between the double quotes. Some examples of strings follow.
"duck"
"duck1"
"duck/soup"
"duck soup"
The third and fourth types of field are numeric fields. A field which represents a
number which can be either an integer or floatingpoint type field. A floating-point
type is commonly referred to simply as a float.
All numbers in CLIPS are treated as long integers or double-precision floats. Numbers
without a decimal point are treated as integers unless they are outside integer range.
The range is machine dependent on the number of bits, N, used to represent the
integer as follows.
- 2N-1 ... 2N-1-1
As some examples of numbers, assert the following data where the last number is in
exponential notation, and uses the "e" or "E" for the power-of-ten.
CLIPS> (facts)
CLIPS> (clear)
<Fact-0>
<Fact-1>
<Fact-2>
<Fact-3>
<Fact-4>
<Fact-5>
<Fact-6>
CLIPS> (facts)
f-0 (number 1)
f-1 (x 1.5)
f-2 (y -1)
f-3 (z 65)
f-5 (coordinates 1 2 3)
< /tt>
f-6 (coordinates 1 3 2)
CLIPS>
As you can see, CLIPS prints the number entered in exponential notation as
350000.0 because it converts from power-of-ten format to floating-point if the
number is small enough.
Notice that each number must start with a symbol such as "number", "x", "y", etc.
Before CLIPS version 6.0, it was possible to enter only a number as a fact. However,
now a symbol is required as the first field. Also, certain reserved words used by
CLIPS cannot be used as the first field, but may be used as others. For example, the
names of predefined CLIPS functions (see Appendix I of the CLIPS Reference
Manual), def-constructs, and so forth cannot be used.
A fact consists of one or more fields enclosed in matching left and right parentheses.
For simplicity we'll only discusss facts in the first seven chapters, but most of the
discussion of pattern matching applies to objects as well. Exceptions are certain
functions such as assert and retract which only apply to facts, not objects. The
corresponding ways to handle objects are discussed in chapters 8-12.
A fact may be ordered or unordered. All the examples you've seen so far are ordered
facts because the order of fields makes a difference. For example, notice that CLIPS
considers these as separate facts although the same values "1", "2", and "3" are used in
each.
f-5 (coordinates 1 2 3)
f-6 (coordinates 1 3 2)
Ordered facts must use field position to define data. As an example, the ordered fact
(duck Brian) has two fields and so does (Brian duck). However, these are considered
as two separate facts by CLIPS because the order of field values is different. In
contrast, the fact (duck-Brian) has only one field because of the "-" concatenating the
two values.
Deftemplate facts, described in more detail later, are unordered because they use
named fields to define data. This is analogous to the use of records in Pascal and other
languages.
Multiple fields normally are separated by white space consisting of one or more
spaces, tabs, carriage returns, or linefeeds. For example, enter the following examples
as shown and you'll see that each stored fact is the same.
CLIPS> (clear)
<Fact-0>
CLIPS> (facts)
CLIPS> (clear)
<Fact-0>
CLIPS> (facts)
CLIPS>
Carriage returns may also be used to improve readability. In the following example, a
carriage return is typed after every field and the asserted fact is the same as before
when the fact was entered on one line.
CLIPS> (clear)
duck
says
"Quack"))
<Fact-0>
CLIPS> (facts)
CLIPS>
duck
says
"Quack
"))
<Fact-1>
CLIPS> (facts)
")
CLIPS>
As you can see, the carriage return embedded in the double quotes was output with the
string to put the closing double quote on the next line. This is important because
CLIPS considers fact f-0 as distinct from fact f-1.
Notice also that CLIPS preserved the uppercase and lowercase letters in the fields of
the fact. That is, the "T" of "The" and the "Q" of "Quack" are uppercase. CLIPS is
said to be case-sensitive because it distinguishes between uppercase and lowercase
letters. For example, assert the facts (duck) and (Duck) and then issue a (facts)
command. You'll see that CLIPS allows you to assert (duck) and (Duck) as different
facts because CLIPS is case-sensitive.
The following example is a more realistic case in which carriage returns are used to
improve the readability of a list. To see this, assert the following fact where carriage
returns and spaces are used to put fields at appropriate places on different lines.
Dashes or minus signs are used intentionally to create single fields, so CLIPS will
treat items like "fudge sauce" as a single field.
CLIPS> (clear)
ice-cream
cookies
candy
fudge-sauce))
<Fact-0>
CLIPS> (facts)
CLIPS>
As you can see, CLIPS replaced the carriage returns and tabs with single spaces.
While the use of white space in separating the facts is convenient for a person reading
a program, they are converted to single spaces by CLIPS.
A Matter of Style
It is good rule-based programming style to use the first field of a fact to describe
the relationship of the following fields. When used this way, the first field is called a
relation. The remaining fields of the fact are used for specific values. An example is
(grocery-list ice-cream cookies candy fudge-sauce). The dashes are used to make
multiple words fit in a single field.
Another example of related facts is (duck), (horse), and (cow). It's better style to refer
to them as
(animal-is duck)
(animal-is horse)
(animal-is cow)
or as the single fact
since the relation animal-is or animals describes their relation and so provides some
documentation to the person reading the code.
The explicit relations, animal-is and animals, make more sense to a person than the
implicit meaning of (duck), (horse), and (cow). While this example is simple enough
that anyone can figure out the implicit relations, it is an easy trap to fall into to write
facts in which the relationship is not so obvious (In fact, it's much easier to make
something more complicated than easy, since people are more impressed by
complexity than simplicity.)
Since spaces are used to separate multiple fields, it follows that spaces cannot simply
be included in facts. For example,
CLIPS> (clear)
<Fact-0>
FALSE
FALSE
CLIPS> (facts)
CLIPS>
Only one fact, (animal-is walrus), is asserted since CLIPS ignores white space
and considers all these facts equivalent. Thus, CLIPS responds with a FALSE
when you try to enter the last two duplicate facts. CLIPS normally does not
allow duplicate facts to be entered unless you change the set-fact-duplicate
setting.
If you want to include spaces in a fact, you must use double quotes. For example,
CLIPS> (clear)
<Fact-0>
<Fact-1>
<Fact-2>
<Fact-3>
CLIPS> (facts)
CLIPS>
Note that the spaces make each of these facts different to CLIPS although the meaning
is the same to a person.
What if you want to include the double quotes in a field? The correct way to put
double quotes in a fact is with the backslash, "", as the following example shows.
CLIPS> (clear)
<Fact-0>
<Fact-1>
CLIPS> (facts)
f-0 (single-quote "duck")
CLIPS>
Now that you know how to put facts into the fact-list, it's time to learn how to remove
them. Removing facts from the fact-list is called retraction and is done with the
retract command. To retract a fact, you must specify the fact index of the fact as the
argument of retract. For example, set up your fact-list as follows.
CLIPS> (clear)
<Fact-0>
<Fact-1>
<Fact-2>
CLIPS> (facts)
CLIPS>
To remove the last fact with index f-2, enter the retract command and then check your
facts as follows.
CLIPS> (retract 2)
CLIPS> (facts)
CLIPS>
What happens if you try to retract a fact that's already retracted, or a non-
existent fact? Let's try it and see.
CLIPS> (retract 2)
CLIPS>
Notice that CLIPS issues an error message if you try to retract a non-existent
fact. The moral of this is that you can't take back what you haven't given.
CLIPS> (facts)
CLIPS> (retract 0)
CLIPS> (facts)
CLIPS>
You can also retract multiple facts at once, as shown by the following.
CLIPS> (clear)
<Fact-0>
<Fact-1>
CLIPS> (retract 0 2)
CLIPS> (facts)
CLIPS>
To retract multiple facts, just list the fact-id numbers in the (retract) command.
You can just use (retract *) to retract all the facts, where the "*" indicates all .
CLIPS> (clear)
<Fact-0>
<Fact-1>
<Fact-2>
CLIPS> (facts)
CLIPS> (retract *)
CLIPS>
CLIPS provides several commands to help you debug programs. One command
allows you to continuously watch facts being asserted and retracted. This is more
convenient than having to type in a (facts) command over and over again and trying to
figure out what's changed in the fact-list.
To start watching facts, enter the command (watch facts) as shown in the following
example.
CLIPS> (clear)
<Fact-0>
CLIPS>
The right double arrow symbol, ==>, means that a fact is entering memory while
the left double arrow indicates a fact is leaving memory, as shown following.
CLIPS> (reset)
<Fact-1>
CLIPS> (retract 1)
CLIPS> (facts)
f-0 (initial-fact)
CLIPS>
The (watch facts) command provides a record that shows the dynamic or changing
state of the fact-list. In contrast, the (facts) command show the static state of the fact-
list since it displays the current contents of the fact-list. To turn off watching facts,
enter (unwatch facts).
There are a number of things you can watch. These include the following, which are
described in more detail in the CLIPS Reference Manual. The comment in CLIPS
begins with a semicolon. Everything after the semicolon is ignored by CLIPS.
(watch facts)
(watch rules)
(watch activations)
(watch generic-functions)
(watch deffunctions)
(watch statistics)
(watch globals)
(watch focus)
As you use more of the capabilities of CLIPS, you'll find these (watch)
commands very helpful in debugging. To turn off a (watch) command, enter an
unwatch command. For example, to turn of watching compilations, enter (unwatch
compilations).
CLIPS has on-line help available. To access the help feature, just enter (help)
and press the carriage return key. In a short while, you'll see a menu of topics. For
more information on using (help), read the help section on HELP_USAGE. To exit
from help, keep pressing the carriage return key until the CLIPS prompt reappears. If
an error message appears that says CLIPS could not find the help file, clips.hlp, you
can find out where CLIPS expected it to be by using the command (help-path).
Chapter 2 Following the Rules
If you want to get anywhere in life, don't break the rules
-- make the rules!
In the previous chapter, you learned about facts. Now you'll see how the rules of an
expert system utilize facts in making a program execute.
To accomplish useful work, an expert system must have rules as well as facts. Since
you've seen how facts are asserted and retracted, it's time to see how rules work. A
rule is similar to an IF THEN statement in a procedural language like Ada, C, or
Pascal. An IF THEN rule can be expressed in a mixture of natural language and
computer language as follows:
IF certain conditions are true
Another term for the above statement is pseudocode, which literally means false code.
While pseudocode cannot be directly executed by the computer, it serves as a very
useful guide to writing executable code. Pseudocode is also helpful in documenting
rules. A translation of rules from natural language to CLIPS is not very difficult if you
keep this IF THEN analogy in mind. As your experience with CLIPS grows, you'll
find that writing rules in CLIPS becomes easy. You can either type rules directly into
CLIPS or load rules in from a file of rules created by a text editor.
The following is a fact, and a rule named duck which is the pseudocode above
expressed in CLIPS syntax. The name of the rule follows immediately after the
keyword defrule. Although you can enter a rule on a single line, it's customary to put
different parts on separate lines to aid readability and editing.
CLIPS> (clear)
<Fact-0>
CLIPS> (defrule duck
(animal-is duck)
=>
CLIPS>
If you type in the rule correctly as shown, you should see the CLIPS prompt reappear.
Otherwise, you'll see an error message. If you get an error message, it is likely that
you misspelled a keyword or left out a parenthesis. Remember, the number of left and
right parentheses always must match in a statement.
The same rule is shown following with comments added to match the parts of the rule.
Also shown is the optional rule-header comment in quotes, "Here comes the quack".
There can be only one rule-header comment and it must be placed after the rule name
and before the first pattern. Although we're only discussing pattern matching against
facts now, more generally a pattern can be matched against a pattern entity.
A pattern entity is either a fact or an instance of a user-defined class. Pattern matching
on objects will be discussed later.
CLIPS tries to match the pattern of the rule against a pattern entity. Of course, white
space consisting of spaces, tabs, and carriage returns may be used to separate the
elements of a rule to improve readability. Other comments begin with a semicolon and
continue until the carriage return key is pressed to terminate a line. Comments are
ignored by CLIPS.
(defrule duck "Here comes the quack" ; Rule header
Entering the same rule name, in this case "duck", will replace any existing rule with
that name. That is, while there can be many rules in CLIPS, there can be only one rule
which is named "duck". This is analogous to other programming languages in which
only one procedure name can be used to uniquely identify a procedure.
(pattern_N)
=>
(action_M)) ; the last ")" balances the opening ; "(" to the left of
"defrule". Be
; sure all your parentheses balance ; or you will get error messages
The entire rule must be surrounded by parentheses. Each of the rule patterns and
actions must be surrounded by parentheses. An action is actually a function which
typically has no return value, but performs some useful action, such as an (assert) or
(retract). For example, an action might be (assert (duck)). Here the function name is
"assert" and its argument is "duck". Notice that we don't want any return value such as
a number. Instead, we want the fact (duck) to be asserted. A function in CLIPS is a
piece of executable code identified by a specific name, which returns a useful value or
performs a useful side-effect, such as (printout).
A rule often has multiple patterns and actions. The number of patterns and actions do
not have to be equal, which is why different indices, N and M, were chosen for the
rule patterns and actions.
Zero or more patterns may be written after the rule header. Each pattern consists of
one or more fields. In the duck rule, the pattern is (animal-is duck), where the fields
are "animal-is" and "duck". CLIPS attempts to match the patterns of rules against
facts in the fact-list. If all the patterns of a rule match facts, the rule is activated and
put on the agenda. The agenda is a collection of activations which are those rules
which match pattern entities. Zero or more activations may be on the agenda.
The symbol "=>" that follows the patterns in a rule is called an arrow. The arrow
represents the beginning of the THEN part of an IF-THEN rule (and may be read as
"implies").
The last part of a rule is the list of zero or more actions that will be executed when the
rule fires. In our example, the one action is to assert the fact (sound-is quack). The
term fires means that CLIPS has selected a certain rule for execution from the agenda.
When multiple activations are on the agenda, CLIPS automatically determines which
activation is appropriate to fire. CLIPS orders the activations on the agenda in terms
of increasing priority or salience.
The part of the rule before the arrow is called the left-hand side (LHS) and the part of
the rule after the arrow is called the right-hand side (RHS). If you enter a (reset)
command, CLIPS memory is cleared and the special fact (initial- fact) is always put
into the fact-list with fact-identifier "f-0". If no patterns are specified, the pattern
(initial-fact) is used for the LHS.
CLIPS always executes the actions on the RHS of the highest priority rule on the
agenda. This rule is then removed from the agenda and the actions of the new highest
salience rule is executed. This process continues until there are no more activations or
a command to stop is encountered.
You can check what's on the agenda with the agenda command. For example,
CLIPS> (agenda)
0 duck: f-0
CLIPS>
The first number "0" is the salience of the "duck" activation, and "f-0" is the fact-
identifier of the fact, (animal-is duck), which matches the activation. If the salience of
a rule is not declared explicitly, CLIPS assigns it the default value of zero, where the
possible salience values range from -10,000 to 10,000. In this book, we'll use the
definition of the term default as meaning the standard way.
If there is only one rule on the agenda, that rule will fire. Since the LHS pattern of the
duck-sound rule is
(animal-is duck)
this pattern will be satisfied by the fact (animal-is duck) and so the duck-sound rule
should fire.
Each field of the pattern is said to be a literal constraint. The term literal means having
a constant value, as opposed to a variable whose value is expected to change. In this
case, the literals are "animal-is" and "duck".
To make a program run, just enter the run command. Type (run) and press the carriage
return key. Then do a (facts) to check that the fact was asserted by the rule.
CLIPS> (run)
CLIPS> (facts)
CLIPS>
Before going on, let's save the duck rule with the save command so that you don't
have to type it in again (if you haven't already saved it in an editor). Just enter a
command such as
(save "duck.clp")
to save the rule from CLIPS memory to disk and name the file "duck.clp" where the
".clp" is simply a convenient extension to remind us this is a CLIPS source code file.
Note that saving the code from CLIPS memory like this will only preserve the
optional rule-header comment in quotes and not any semicolon comments.
An interesting question may occur to you at this time. What if you (run) again? There
is a rule and a fact which satisfies the rule, so the rule should fire. However, if you try
this and (run) again, you'll see that the rule won't fire. This may be somewhat
frustrating. However, before you do something drastic to ease your frustration -- like
kicking your pet duck -- you need to know a little more about some basic principles of
expert systems.
1. a brand new pattern entity that did not exist before or,
2. a pattern entity that did exist before but was retracted and reasserted, i.e., a "clone"
of the old pattern entity, and thus now a new pattern entity.
The rule, and indices of the matching patterns, is the activation. If either the rule or
the pattern entity, or both change, the activation is removed. An activation may also
be removed by a command or an action of another rule that fired before and removed
the conditions necessary for activation.
The Inference Engine sorts the activations according to their salience. This sorting
process is called conflict resolution because it eliminates the conflict of deciding
which rule should fired next. CLIPS executes the RHS of the rule with the highest
salience on the agenda, and removes the activation. This execution is called firing the
rule in analogy with the firing of a neuron. A neuron emits a voltage pulse when an
appropriate stimulus is applied. After a neuron fires, it undergoes refraction and
cannot fire again for a certain period of time. Without refraction, neurons would just
keep firing over and over again on exactly the same stimulus.
Without refraction, expert systems always would be caught in trivial loops. That is, as
soon as a rule fired, it would keep firing on that same fact over and over again. In the
real world, the stimulus that caused the firing eventually would disappear. For
example, a real duck might swim away or get a job in the movies. However, in the
computer world, once data is stored, it stays there until explicitly removed or the
power is turned off.
The following example shows activations and firing of a rule. Notice that the (watch)
commands are used to more carefully show every fact and activation. The arrow going
to the right means an entering fact or activation while an arrow to the left would mean
an exiting fact or activation.
CLIPS> (clear)
(animal-is duck)
=>
CLIPS> (agenda)
0 duck: f-0
CLIPS> (run)
quack
CLIPS> (run)
CLIPS>
You can make the rule fire again if you retract the fact and then assert it as a new fact.
Sometimes you may want to see a rule while you're in CLIPS. There's a command
called ppdefrule - the pretty print rule - that prints a rule. To see a rule, specify the
rule name as argument to pprule. For example,
CLIPS> (ppdefrule duck)
(defrule MAIN::duck
(animal-is duck)
=>
CLIPS>
CLIPS puts different parts of the rule on different lines for the sake of readability. The
patterns before the arrow are still considered the LHS and the actions after the arrow
are still considered the RHS of the rule. The term MAIN refers to the MAIN module
that this rule is in by default. You can define modules to put rules in analogous to the
statements that may be put in different packages, modules, procedures, or functions of
other programming languages. The use of modules make it easier to write expert
systems having many rules since these may be grouped together with their own
agendas for each module. For more information, see the CLIPS Reference Manual.
What if you want to print a rule but can't remember the name of the rule? No problem.
Just use the rules command in response to a CLIPS prompt and CLIPS will print out
the names of all the rules. For example, enter
CLIPS> (rules)
duck
CLIPS>
Write to Me
Besides asserting facts in the RHS of rules, you also can print out information using
the printout function. CLIPS also has a carriage return/linefeed keyword called crlf
which is very useful in improving the appearance of output by formatting it on
different lines. For a change, the crlf is not included in parentheses. As an example,
CLIPS> (defrule duck
(animal-is duck)
=>
quack
CLIPS>
The output is the text within the double quotes. Be sure to type the letter "t" following
the printout command. This tells CLIPS to send the output to the standard output
device of your computer. Generally, the standard output device is your terminal
(hence the letter "t" after printout.) However, this may be redefined so that the
standard output device is some other device, such as a modem or disk.
Other Features
The declare salience command provides explicit control over which rules will be put
on the agenda. You must be careful in using this feature too freely lest your program
become too controlled. The set-incremental-reset command prohibits rules from
seeing facts that are entered before the rules are entered. The command to get the
current value of incremental reset is getincrementalreset. One way to make a rule fire
again is to force the rule to be re-activated by the refresh rule command.
The load command loads in the rule that you had previously saved to disk in the file
"duck.clp" or whatever name and directory that you had saved it under. You can load
a file of rules made on a text editor into CLIPS using the load command.
A faster way to load files is to first save them in a machine readable binary format
with the save binary command called bsave. The load binary command, bload, can
then be used to read these binary rules into CLIPS memory much faster since the files
do not have to be re-interpreted by CLIPS.
Two other useful commands allow you to save and load facts using a file. These are
save-facts and load-facts. The (save-facts) will save all the facts in the fact-list to a
file while (load-facts) will load in the facts from a file into the fact-list.
The batch command allows you to execute commands from a file as if they were
typed in at the top-level.Another useful command provides an interface to your
operating system. The system command allows the execution of operating system
commands or executables within CLIPS. For more information on all these topics, see
the CLIPS Reference Manual.
Stop And Go
Until now, you've only seen the simplest type of program consisting of just one rule.
However, expert systems consisting of only one rule are not very useful. Practical
expert systems may consist of hundreds or thousands of rules. Let's now take a look at
an application requiring multiple rules.
Suppose you wanted to write an expert system to determine how a mobile robot
should respond to a traffic light. It is best to write this type of problem using multiple
rules. For example, the rules for the red and green light situations can be written as
follows.
(defrule red-light
(light red)
=>
(defrule green-light
(light green)
=>
After the rules have been entered into CLIPS, assert a fact (light red) and run. You'll
see "Stop" printed. Now assert a (light green) fact and run. You should see "Go"
printed.
Take a Walk
If you think about it, other possibilities beside the simple red, green, and yellow cases
exist. Some traffic lights also have a green arrow for protected left turns. Some have a
hand that lights up to indicate whether a person can walk or not. Some have signs that
say walk or don't walk. So depending on whether our robot is walking or driving, it
may have to pay attention to different signs.
(status walking)
(walk-sign walk)
=>
The above rule has two patterns. Both patterns must be satisfied by facts in the fact-
list for the rule to fire. To see how this works, enter the rule and then assert the facts
(status walking) and (walk-sign walk). When you (run), the program will print out
"Go" since both patterns are satisfied and the rule is fired.
You can have any number of patterns or actions in a rule. The important point to
realize is that the rule is placed on the agenda only if all the patterns are satisfied by
facts. This type of restriction is called a logical AND conditional element (CE)in
reference to the AND relation of Boolean logic. An AND relation is said to be true
only if all its conditions are true.
Because the patterns are of the logical AND type, the rule will not fire if only one of
the patterns is satisfied. All facts must be present before the LHS of a rule is satisfied
and the rule is placed on the agenda.
A Question of Strategy
The word strategy was originally a military term for the planning and operations of
warfare. Today, the term strategy is commonly used in business (because business is
war) to refer to the high-level plans of an organization in achieving its goals, e.g.,
"Make a lot of money by selling more greasy hamburgers than anyone else in the
world!"
In expert systems, one use of the term strategy is in conflict resolution of activations.
Now you might say, "Well, I'll just design my expert system so that only one rule can
possibly be activated at one time. Then there is no need for conflict resolution." The
good news is that if you succeed, conflict resolution is indeed unnecessary. The bad
news is that this success proves that your application can be well represented by a
sequential program. So you should have coded it in Ada, C, or Pascal in the first place
and not bothered writing it as an expert system.
CLIPS offers seven different modes of conflict resolution: depth, breadth, LEX,
MEA, complexity, simplicity, and random. It's difficult to say that one is clearly better
than another without considering the specific application. Even then, it may be
difficult to judge which is "best." For more information on the details of these
strategies, see the CLIPS Reference Manual.
The depth strategy is the standard default strategy of CLIPS. The default setting is
automatically set when CLIPS is first started. Afterwards, you can change the default
setting. In the depth strategy, new activations are placed on the agenda after
activations with higher salience, but before activations with equal or lower salience.
All this simply means is that the agenda is ordered from highest to lowest salience.
In this book, all discussions and examples will assume depth strategy.
Now that all these different optional settings are available, be sure that before you run
an expert system developed by someone else, that your settings are the same as theirs.
Otherwise, you may find the operation is inefficient or even incorrect. In fact, it's a
good idea to explicitly encode all the settings in any system that you develop so that it
will be configured properly.
Gimme Deffacts
As you work with CLIPS, you may become tired of typing in the same assertions from
the top-level. If you are going to use the same assertions every time a program is run,
you can first load assertions from a disk using a batch file. An alternative way to enter
facts is by using the define facts keyword, deffacts. For example,
CLIPS> (clear)
CLIPS> (facts)
f-0 (initial-fact)
CLIPS>
The required name of this deffacts statement, walk, follows the deffacts keyword.
Following the name is an optional comment in double quotes. Like the optional
comment of a rule, the (deffacts) comment will be retained with the (deffacts) after it's
been loaded by CLIPS. After the name or comment are the facts that will be asserted
in the fact-list. The facts in a deffacts statement are asserted using the CLIPS (reset)
command.
The (reset) has a further advantage compared to a (clear) command in that (reset)
doesn't get rid of all the rules. The (reset) leaves your rules intact. Like (clear), it
removes all activated rules from the agenda and also removes all old facts from the
fact-list. Giving a (reset) command is a recommended way to start off program
execution, especially if the program has been run before and the fact-list is cluttered
with old facts.
(1) It removes existing facts from the fact-list, which may remove activated rules from
the agenda.
Selective Elimination
The undeffacts command excises a (deffacts) from asserting facts by eliminating the
deffacts from memory. For example,
CLIPS> (undeffacts walk)
CLIPS> (reset)
CLIPS> (facts)
f-0 (initial-fact)
CLIPS>
This example demonstrates how the (deffacts) walk has been excised. To restore a
deffacts statement after an (undeffacts) command, you must enter the deffacts
statement again. You can even get rid of initial-fact with (undeffacts). In addition to
facts, CLIPS also allows you to eliminate rules selectively by using the undefrule.
Watch It!
You can watch rules firing and watch activations on the agend. The watch statistics
prints information about the number of rules fired, run time, rules per second, mean
number of facts, maximum number of facts, mean number of activations, and
maximum number of activations. The statistics information may be useful in tuning
up an expert system to optimize its speed. Another command, called watch
compilations, shows information when rules are being loaded. The watch
all command will watch everything.
Printing of watch information to the screen or to disk with the dribble command will
slow down your program somewhat because CLIPS uses more time to print or to save
to disk. The dribble-on command will store everything entered in the Dialog
Window to a disk file until the dribble-off command is entered. This is convenient in
providing a permanent record of everything that happens. These commands are as
follows.
(dribble-on <filename>)
(dribble-off <filename>)
Another useful debugging command is (run) which takes an optional argument of the
number of rule firings. For example, a (run 21) command would tell CLIPS to run the
program and then stop after 21 rule firings. A (run 1) command allows you to step
through a program firing one rule at a time. The (step) command is equivalent to
(run 1).
Just like many other programming languages, CLIPS also gives you the capability of
setting breakpoints. A breakpoint is simply an indicator to CLIPS to stop execution
just prior to executing a specified rule. A breakpoint is set by the setbreak command.
The remove-break command will remove a breakpoint that has been set. The show-
breaks will list all the rules which have breakpoints set. The syntax of these rules for
the argument <rulename> is shown following.
(set-break <rulename>)
(remove-break <rulename>)
(show-breaks)
A Good Match
You may encounter a situation in which you are certain a rule should be activated but
isn't. While it is possible that this is due to a bug in CLIPS, it's not very likely because
of the great skill of the people who programmed CLIPS (NOTE: PAID
COMMERCIAL ANNOUNCEMENT FOR THE DEVELOPERS)
In most cases, the problem occurs because of the way that you wrote the rule. As an
aid to debugging, CLIPS has a command called matches that can tell you which
patterns in a rule match facts. Patterns which do not match prevent the rule from
becoming activated. One common reason that a pattern won't match a fact results from
misspelling an element in the pattern or in the assertion of the fact.
The argument of (matches) is the name of the rule to be checked for matches. To see
how (matches) works, first (clear), then enter the following rule.
(defrule take-a-vacation
=>
The following shows how (matches) is used. Enter the commands as shown. Notice
that (watch facts) is turned on. This is a good idea when you are asserting facts
manually since it gives you an opportunity to check the spelling of facts.
CLIPS> (assert (work done))
<Fact-0>
f-0
None
None
None
None
Activations
None
CLIPS>
The fact with fact-identifier f-1 matches the first pattern or conditional element in the
rule and is reported by (matches). Given that a rule has N patterns, the term partial
matches refers to any set of matches of the first N-1 patterns with facts. That is, the
partial matches begin with the first pattern in a rule and end with any pattern up to but
not including the last (Nth) pattern. As soon as one partial match cannot be made,
CLIPS does not check any further. For example, a rule with four patterns would have
partial matches of the first and second patterns and also of the first, second, and third
patterns. If all N patterns match, the rule will be activated.
Other Features
Some additional commands are useful with deffacts. For example, the command
listdeffacts will list the names of currently loaded deffacts in CLIPS. Another useful
command is ppdeffacts which prints the facts stored in a deffacts.
Other functions allow you to manipulate strings easily.
Function Meaning
If you want to printout a multifield variable without parentheses, the simplest way is
by using the string implode function, implode$.
The type of rules that you've seen so far illustrates simple matching of patterns to
facts. In this chapter, you'll learn very powerful ways to match and manipulate facts.
Just as with other programming languages, CLIPS has variables to store values.
Unlike a fact, which is static or unchanging, the contents of a variable are dynamic as
the values assigned to it change. In contrast, once a fact is asserted, it's fields can only
be modified by retracting and asserting a new fact with the changed fields, Even
the modify action (described later in the chapter on deftemplate) acts by retracting and
asserting a modified fact, as you can see by checking the fact-index.
=>
(printout t ?x crlf))
ERROR:
(defrule MAIN::test
(initial-fact)
=>
(printout t ?x crlf))
CLIPS>
CLIPS gives an error message when it cannot find a value bound to ?x. The
term bound means the assignment of a value to a variable. Only global variables are
bound in all rules. All other variables are only bound within a rule. Before and after a
rule fires, nonglobal variables are not bound and so CLIPS will give an error message
if you try to query a nonbound variable.
Be Assertive
One common use of variables is to match a value on the LHS and then assert this
bound variable on the RHS. For example, enter
(defrule make-quack
(duck-sound ?sound)
=>
Now assert (duck-sound quack), then (run) the program. Check the facts and you'll see
that the rule has produced (sound-is quack) because the variable ?sound was bound to
quack.
Of course, you also can use a variable more than once. For example, enter the
following. Be sure to do a (reset) and assert (duck-sound quack) again.
(defrule make-quack
(duck-sound ?sound)
=>
When the rule fires, it will produce (sound-is quack quack) since the variable ?sound
is used twice.
(duck-sound ?sound)
=>
Do a (reset), enter this rule, and assert the fact and then (run) to find out what the duck
said. How would you modify the rule to put double quotes around quack in the
output?
More than one variable may be used in a pattern, as the following example shows.
CLIPS> (clear)
=>
CLIPS> (reset)
<Fact-1>
CLIPS> (run)
<Fact-2>
CLIPS> (run)
<Fact-3>
CLIPS> (run)
Notice what a big difference the order of fields makes in determining who shot who.
You can also see that the rule did not fire when the single-field fact (duck) was
asserted. The rule was not activated because no field of the fact matched the second
pattern constraint, ?who.
Retraction is very useful in expert systems and usually done on the RHS rather than at
the top-level. Before a fact can be retracted, it must be specified to CLIPS. To retract
a fact from a rule, the fact-address first must be bound to a variable on the LHS.
There is a big difference between binding a variable to the contents of a fact and
binding a variable to the fact-address. In the examples that you've seen such as (duck-
sound ?sound), a variable was bound to the value of a field. That is, ?sound was
bound to quack. However, if you want to remove the fact whose contents are (duck-
sound quack), you must first tell CLIPS the address of the fact to be retracted.
The fact-address is specified using the left arrow, "<-". To create this, just type a "<"
symbol followed by a "-". As an example of fact retraction from a rule,
CLIPS> (clear)
<Fact-0>
CLIPS> (facts)
=>
(retract ?duck))
CLIPS> (run)
CLIPS> (facts)
CLIPS>
Notice that the (printout) prints the fact- index of ?duck, <Fact-0>, since the left arrow
bound the address of the fact to ?duck. Also, there is no fact (bachelor Dopey)
because it has been retracted.
Variables can be used to pick up a fact value at the same time as an address, as shown
in the following example. For convenience, a (deffacts) has also been defined.
CLIPS> (clear)
(retract ?duck))
(bachelor Dopey)
(bachelor Dorky)
(bachelor Dicky))
CLIPS> (reset)
CLIPS> (run)
CLIPS>
Notice how the rule fired on all facts that matched the pattern (bachelor ?name).
CLIPS also has a function called fact-index which can be used to return the fact index
of a fact address.
Instead of binding a field value to a variable, the presence of a nonempty field can be
detected alone using a wildcard. For example, suppose you're running a dating service
for ducks, and a duckette asserts that she only dates ducks whose first name is
Richard. Actually, two criteria are in this specification since there is an implication
that the duck must have more than one name. So a plain (bachelor Richard) isn't
adequate because there is only one name in the fact.
This type of situation, in which only part of the fact is specified, is very common and
very important. To solve this problem, a wildcard can be used to fire the Richards.
(bachelor Dopey ?)
=>
CLIPS>
(deffacts duck
(bachelor Dicky)
(bachelor Dopey)
CLIPS> (reset)
CLIPS> (run)
Date Dopey
CLIPS>
The pattern includes a wildcard to indicate that Dopey's last name is not important. So
long as the first name is Dopey, the rule will be satisfied and fire. Because the pattern
has three fields of which one is a single-field wildcard, only facts of exactly three
fields can satisfy it. In other words, only Dopeys with exactly two names can satisfy
this duckette.
Suppose you want to specify Dopeys with exactly three names? All that you'd have to
do is write a pattern like
(bachelor Dopey ? ?)
or, if only persons with three names whose middle name was Dopey,
(bachelor ? Dopey ?)
(bachelor Dopey ?)
=>
(defrule eligible-three-names
(bachelor Dopey ? ?)
=>
Enter and run this and you'll see that Dopeys with both two and three names are
printed. Of course, if you don't want anonymous dates, you need to bind the Dopey
names with a variable and print them out.
Going Wild
Rather than writing separate rules to handle each field, it's much easier to use the
multifield wildcard. This is a dollar sign followed by a question mark, "$?", and
represents zero or more fields. Notice how this contrasts with the single-field wildcard
which must match exactly one field.
The two rules for dates can now be written in a single rule as follows.
CLIPS> (clear)
=>
(bachelor Dicky)
(bachelor Dopey)
CLIPS> (reset)
CLIPS> (run)
Date Dopey
Date Dopey
Date Dopey
CLIPS>
Wildcards have another important use because they can be attached to a symbolic
field to create a variable such as ?x, $?x, ?name, or $?name. The variable can be a
singlefield variable or a multifield variable depending on whether a "?" or "$?" is used
on the LHS. Note that on the RHS only a ?x is used, where the "x" can be any variable
name. You can think of the "$" as a function whose argument is a single-field
wildcard or a single-field variable and returns a multifield wildcard or a multifield
variable, respectively.
As an example of a multifield variable, the following version of the rule also prints
out the name field(s) of the matching fact because a variable is equated to the name
field(s) that match:
CLIPS> (defrule dating-ducks
=>
CLIPS> (reset)
CLIPS> (run)
CLIPS>
As you can see, on the LHS, the multifield pattern is $?name but is ?name when used
as a variable on the RHS. When you enter and run, you'll see the names of all eligible
Dopeys. The multifield wildcard takes care of any number of fields. Also, notice that
multifield values are returned enclosed in parentheses.
Suppose you wanted a match of all ducks who had a Dopey somewhere in their name,
not necessarily as their first name. The following version of the rule would match all
facts with a Dopey in them and then print out the names:
CLIPS> (defrule dating-ducks
=>
CLIPS> (reset)
CLIPS> (run)
Date () Dopey ()
CLIPS>
The pattern matches any names that have a Dopey anywhere in them.
Single- and multifield wildcards can be combined. For example, the pattern
(bachelor ? $? Dopey ?)
means that the first and last names can be anything and that the name just prior to the
last must be Dopey. This pattern also requires that the matching fact will have at least
four fields, since the "$?" matches zero or more fields and all the others must
match exactly four.
Although multifield variables can be essential for pattern matching in many cases,
their overuse can cause much inefficiency because of increased memory requirements
and slower execution.
_ As a general rule of style, you should use $? only when you don't know the length of
fields. Do not use $? simply as a typing convenience.
Variables used in patterns have an important and useful property, which can be stated
as follows.
_ The first time a variable is bound it retains that value only within the rule, both on
the LHS and also on the RHS, unless changed on the RHS.
(number-1 ?num)
(number-2 ?num)
=>)
f-1 (number-2 0)
f-2 (number-1 1)
f-3 (number-2 1)
then the rule can only be activated by the pair f-0, f-1, and the other pair f-2, f-3. That
is, fact f-0 cannot match with f-3 because when ?num is bound to 0 in the first pattern,
the value of ?num in the second pattern also must be 0. Likewise, when ?num is bound
to 1 in the first pattern, the value of ?num in the second pattern must be 1. Notice that
the rule will be activated twice by these four facts: one activation for the pair f-0, f-1,
and the other activation for the pair f-2, f-3.
As a more practical example, enter the following rule. Notice that the same variable, ?
name, is used in both patterns. Before doing a (reset) and (run), also enter a (watch
all) command so that you can see what happens during execution.
CLIPS> (clear)
=>
CLIPS> (reset)
CLIPS> (run)
CLIPS>
When the program is run, the first pattern matches Dopey and Dorky since they both
have big bills. The variable ?name is bound to each name. When CLIPS tries to match
the second pattern of the rule, only the variable ?name which is bound to Dopey also
satisfies the second pattern of (feet wide).
Many situations occur in life where it's wise to do things in a systematic manner. That
way, if your expectations don't work out you can try again systematically (such as the
common algorithm for finding the Perfect Spouse by getting married over and over
again).
One way of being organized is to keep a list (Note: if you really want to impress
people, show them a list of your lists.) In our case, we'll keep a list of duck bachelors,
with the most likely prospect for matrimony at the front. Once an ideal duck bachelor
has been identified, we'll shoot him up to the front of the list as the lucky duck.
The following program shows how this can be done by adding a couple of rules to the
ideal ?duck-bachelor rule.
(defrule ideal-duck-bachelor
=>
(defrule move-to-front
=>
(defrule print-list
(list $?list)
=>
(retract ?change-list)
(deffacts duck-bachelor-list
(deffacts duck-assets
(bill big Dicky)
The original list is given in the duck ?duck-bachelor-list deffacts. When the program
is run, it will provide a new list of likely candidates.
CLIPS> (reset)
CLIPS> (run)
CLIPS>
Notice the assertion (change-list yes) in the move-to-front rule. Without this assertion,
the print-list rule would always fire on the original list. This assertion is an example of
a control fact made to control the firing of another rule. Control facts are very
important in controlling the activation of certain rules, and you should study this
example carefully to understand why it's used. Another method of control is modules,
as discussed in the CLIPS Reference Manual.
The move-to-front rule removes the old list and asserts the new list. If the old list was
not retracted, two activations would be on the agenda for the print-list rule but only
one would fire. Only one will fire because the print-list rule removes the control fact
required for the other activation of the same rule. You would not know in advance
which one would fire, so the old list might be printed instead of the new list.
In this chapter, you will learn about a keyword called deftemplate, which stands for
define template. This feature can aid you in writing rules whose patterns have a well-
defined structure.
Mr. Wonderful
Attributes Value
A deftemplate may be defined for the relation prospect as follows, where white space
and comments are used for readability and explanation.
(deftemplate prospect ;name of deftemplate relation
_ The field type, which can be any one of the allowed types:
SYMBOL, STRING, NUMBER, and others.
This particular deftemplate has three single-slot slots called name, assets, and age.
The deftemplate default values are inserted by CLIPS when a (reset) is done if no
explicit values are defined. For example, enter the deftemplate for prospect, and assert
it as shown.
CLIPS> (assert (prospect))
<Fact-0>
CLIPS> (facts)
CLIPS>
As you can see, CLIPS has inserted the default value of the null string, "", for the
name field since that is the default for a STRING. Likewise, the assets and age
defaults were also inserted by CLIPS. Different types have different default symbols
such as the null string, "", for STRING; the integer 0 for INTEGER; the float 0.0 for
FLOAT and so on. The ?DERIVE keyword selects the appropriate type of constraint
for that slot, e.g., the null string , "", for a slot of type STRING.
You can explicitly set the field values, as the following example shows.
CLIPS> (assert (prospect (age 99) (name "Dopey"))))
CLIPS> (facts)
CLIPS>
Note that the order that the fields are typed in does not matter since these are named
fields.
In the deftemplate, it's important to realize that NUMBER is not a primitive field type
like symbol, string, integer, and float. The NUMBER is really a compound type that
can be integer or float. It is used for cases in which the user doesn't care what type of
numbers are stored. An alternative to NUMBER would be specifying the types as
follows.
(slot age
(default 80)))
Bye-Bye
(slot-1)
(slot-2)
...
(slot-N))
In a deftemplate, the attribute values may be specified more precisely than a simple
value such as 80 or rich. For example, in this deftemplate, a type of value is specified.
The field values can be specified by either explicitly listing them or giving a range of
values. The allowed-values can be any primitive type such as SYMBOL, STRING,
INTEGER, FLOAT and so on. For example,
Deftemplate Enumerated Values Example
allowed-symbols rich filthy-rich loaded
allowed-integers -100 53
It doesn't make sense to specify both a numeric range and values allowed for the same
deftemplate field. For example, if you specify (allowed-integers 1 4 8), this
contradicts a range specification of 1 to 10 by (range 1 10). If the numbers happen to
be sequential, such as 1, 2, 3, then you could specify a range which would exactly
match: (range 1 3). However, the range would be redundant to the allowed-integers
specification. Thus, range and allowed values are mutually exclusive. That is, if you
specify a range, you can't specify the allowed values and vice versa. In general, the
range attribute cannot be used in conjunction with allowed-values, allowed-numbers,
allowed-integers, or allowed-floats.
Without the optional information, the deftemplate and a rule which uses it follows.
(clear)
(defrule matrimonial_candidate
=>
<Fact-0>
CLIPS> (run)
rich
99 months old
CLIPS>
Notice that the default value of rich was used for Dopey since the assets field was not
specified in the assert command.
If the assets field is given a specific value such as poor, the specified value
for assets of poor overrides the default value of rich as shown in the following
example about Dopey's penurious nephew.
CLIPS> (reset)
CLIPS> (run)
poor
95 months old
A deftemplate pattern may be used just like any ordinary pattern. For example, the
following rule will eliminate undesirable prospects.
CLIPS> (undefrule matrimonial_candidate)
=>
(retract ?bad-prospect)
CLIPS> (reset)
<Fact-1>
<Fact-2>
CLIPS> (run)
CLIPS>
Ain't No Strings on Me
Notice that only single fields were used for the patterns in the examples so far. That is,
the field values for name, assets, and age, were all single values. In some types of
rules, you may want multiple fields. Deftemplate allows the use of multiple values in
a multislot.
As an example of multislot, suppose that you wanted to treat the name of the
relation prospect as multiple fields. This would provide more flexibility in processing
prospects since any part of the name could be pattern matched. Shown following is
the deftemplate definition using multislot and the revised rule to pattern match on
multiple fields. Notice that a multislot pattern, $?name, is now used to match all the
fields that make up the name. For convenience, a (deffacts) is also given.
CLIPS> (clear)
(multislot name
(type SYMBOL)
(default ?DERIVE))
(slot assets
(type SYMBOL)
(allowed-symbols poor rich wealthy loaded)
(default rich))
(slot age
(type INTEGER)
(default 80)))
=>
?net_worth crlf
CLIPS> (reset)
CLIPS> (run)
rich
99 months old
CLIPS>
In the output, the parentheses around Dopey's name are put in by CLIPS to indicate
that this is a multislot value. If you compare the output from this multislot version to
the single-slot version, you'll see that the double quotes around "Dopey Wonderful"
are gone. The name slot is not a string in the multislot version, so CLIPS treats the
name as two independent fields, Dopey and Wonderful.
What's in a Name
Deftemplate greatly simplifies accessing a specific field in a pattern because the
desired field can be identified by its slot name. The modify action can be used to
retract and assert a new fact in one action by specifying one or more template slots to
be modified.
As an example, consider the following rules which show what happens when duck-
bachelor Dopey Wonderful loses all his fish buying Donald Duck posters and banana
fishsplits for his new duckette, Dixie.
CLIPS> (undefrule *)
CLIPS>
(defrule make-bad-buys
(assets rich)
(age ?months))
=>
"rich" crlf
CLIPS>
(defrule poor-prospect
(assets poor)
(age ?months))
=>
poor crlf
CLIPS> (reset)
CLIPS> (run)
rich
99 months old
poor
99 months old
CLIPS>
If you do a (facts) command as follows, you'll see that the f-1 fact corresponding to
(prospect (assets rich) (age 99) (name Dopey Wonderful)) is gone since the (modify)
has retracted it and asserted f-2.
CLIPS> (facts)
f-0 (initial-fact)
CLIPS>
The make-bad- buys rule is activated by a rich prospect as specified by the assets slot.
This rule changes the assets to poor using the modify action. Notice that the
slot assets can be accessed by name. Without a deftemplate, it would be necessary to
enumerate all the fields by single variables or by using a wildcard, which is less
efficient. The purpose of the poor- prospect rule is simply to print out the poor
prospects, thus demonstrating that the make-bad-investments rule did indeed modify
the assets.
Not My Constraint
Let's reconsider the problem of designing an expert system to help a robot cross a
street. One rule that you would have follows.
(defrule green-light
(light green)
=>
(light red)
=>
A third rule would cover the case in which a walk-sign said not to walk. This would
take precedence over a green light.
(defrule walk-sign
(walk-sign-says dont-walk)
=>
The previous rules are simplified and don't cover all cases such as the breakdown of
the traffic-light. For example, what does the robot do if the light is red or yellow and
the walk-sign says walk?
A way of handling this case is to use a field constraint to restrict the values that a
pattern may have on the LHS. The field constraint acts like constraints on patterns.
One type of field constraint is called a connective constraint. There are three types of
connective constraints. The first is called a ~ constraint. Its symbol is the tilde "~".
The ~ constraint acts on the one value that immediately follows it and will not allow
that value.
As a simple example of the ~ constraint, suppose you wanted to write a rule that
would print out "Don't walk" if the light was not green. One approach would be to
write rules for every possible light condition, including all possible malfunctions:
yellow, red, blinking yellow, blinking red, blinking green, winking yellow, blinking
yellow and winking red, and so forth. However, a much easier approach is to use the ~
constraint as shown in the following rule:
(defrule walk
(light ~green)
=>
By using the ~ constraint, this one rule does the work of many other rules that
required specifying each light condition.
Be Cautious
The second connective constraint is the bar constraint, "|". The "|" connective
constraint is used to allow any of a group of values to match.
For example, suppose you wanted a rule that printed out "Be cautious" if the light was
yellow or blinking yellow. The following example shows how it's done using the "|"
constraint.
CLIPS> (clear)
(light yellow|blinking-yellow)
=>
CLIPS>
<Fact-1>
CLIPS> (agenda)
0 cautious: f-1
0 cautious: f-0
CLIPS>
And Away We Go
The third type of connective constraint is the & connective constraint. The symbol of
the & connective constraint is the ampersand, "&". The & constraint forces connected
constraints to match in union, as you'll see in the following examples. The &
constraint normally is used only with the other constraints, otherwise it's not of much
practical use. As an e xample, suppose you want to have a rule that will be triggered
by a yellow or blinking-yellow fact. That's easy enough--just use the | connective
constraint as you did in a previous example. But suppose that you also want to
identify the light color?
The solution is to bind a variable to the color that is matched using the "&" and then
print out the variable. This is where the "&" is useful, as shown below.
(defrule cautious
(light ?color&yellow|blinking-yellow)
=>
The variable ?color will be bound to whatever color is matched by the field yellow|
blinking-yellow.
The "&" also is useful with the "~". For example, suppose you want a rule that
triggers when the light is not yellow and not red.
(defrule not-yellow-red
(light ?color&~red&~yellow)
=>
It's Elementary
Besides dealing with symbolic facts, CLIPS also can perform numeric calculations.
However, you should keep in mind that an expert system language like CLIPS is not
primarily designed for number-crunching. Although the math functions of CLIPS are
very powerful, they are really meant for modification of numbers that are being
reasoned about by the application program. Other languages such as FORTRAN are
better for number-crunching in which little or no symbolic reasoning is being done.
You'll find the computational capability of CLIPS useful in many applications.
CLIPS provides basic arithmetic and math functions +, /, *, -, div, max, min, abs,
float, and integer. For more details, see the CLIPS Reference Manual.
Numeric expressions are represented in CLIPS according to the style of LISP. In both
LISP and CLIPS, a numeric expression that customarily would be written as 2 + 3
must be written in prefix form, (+ 2 3). In the prefix form of CLIPS, the function
precedes the arguments, and parentheses must surround the numeric expression. The
customary way of writing numeric expressions is called infix form because the math
functions are fixed in between the arguments.
Functions can be used on the LHS and the RHS. For example, the following shows
how the arithmetic operation of addition is used on the RHS of a rule to assert a fact
containing the sum of two numbers ?x and ?y. Note that the comments are in infix
notation for your information only since infix cannot be evaluated by CLIPS.
CLIPS> (clear)
(numbers ?x ?y)
=>
<Fact-0>
CLIPS> (run)
CLIPS> (facts)
f-0 (numbers 2 3)
f-1 (answer-plus 5)
CLIPS>
A function can be used on the LHS if an equal sign, =, is used to tell CLIPS to
evaluate the following expression rather than use it literally for pattern matching. The
following example shows how the hypotenuse is calculated on the LHS and used to
pattern match against some stock items. The exponentiation, "**", function is used to
square the x and y values. The first argument of exponentiation is the number which is
to be raised to the power of the second argument.
CLIPS> (clear)
(stock A 2.0)
(stock B 5.0)
(stock C 7.0))
(numbers ?x ?y)
=>
CLIPS> (reset)
<Fact-4>
CLIPS> (run)
CLIPS>
Extensive Arguments
Arguments in a numeric expression can be extended beyond two for all functions
except The same sequence of arithmetic calculations is performed for more than two
arguments. The following example illustrates how three arguments are used.
Evaluation proceeds from left to right. Before entering these, however, you may wish
to do a (clear) to get rid of any old facts and rules.
(defrule addition
(numbers ?x ?y ?z)
=>
Enter the above program and assert (numbers 2 3 4). After you run, you'll see the
following facts. Note that the fact-indices may be different if you've done a (reset)
instead of a (clear) before loading this program.
CLIPS> (facts)
f-0 (numbers 2 3 4)
f-1 (answer-plus 9)
CLIPS>
where the square brackets mean that there can be multiple terms.
Besides the basic math functions, CLIPS has Extended Math functions including trig,
hyperbolic, and so on. For a complete list, see the CLIPS Reference Manual. These
are called Extended Math functions because they are not considered basic math
functions like "+", "-", etc.
Mixed Results
In dealing with expressions, CLIPS tries to keep the mode the same as the arguments.
For example,
CLIPS> (+ 2 2) ;both integer arguments give integer
4 ;result
4.0
Notice that in the last case of mixed arguments, CLIPS converts the result to standard
double-precision floating-point type.
You can explicitly convert one type to another by using the float and integer
functions, as demonstrated in the following examples.
CLIPS> (float (+ 2 2)) ;convert integer to float
4.0
Parentheses are used to explicitly specify the order of expression evaluation if desired.
In the example of ?x + ?y * ?z, the customary infix way to evaluate it is to multiply ?y
by ?z and then add the result to ?x. However, in CLIPS, you must write the
precedence explicitly if you want this order of evaluation, as follows.
(defrule mixed-calc
(numbers ?x ?y ?z)
=>
Bound Bachelors
(numbers ?x ?y)
=>
CLIPS>
<Fact-0>
CLIPS> (run)
answer is 4
CLIPS> (facts)
f-0 (numbers 2 2)
f-1 (answer 4)
CLIPS>
The (bind) also can be used on the RHS to bind sin gle or multifield values to a
variable. The (bind) is used to bind zero, one, or more values to a variable without the
"$" operator. Recall that on the LHS, you can only create a multifield pattern by using
the "$" operator on a field, such as "$?x". However, the "$" is unnecessary on the
RHS because the arguments of (bind) explicitly tell CLIPS exactly how many values
to bind. In fact, the "$" is a useless appendage on the RHS.
The following rule illustrates some variable bindings on the RHS. The multifield
value function, create$, is used to create a multifield value. Its general syntax is as
follows.
(create$ <arg1> <arg2>...<argN>)
where any number of arguments can be appended together to create a multifield value.
This multifield value, or a single-field value, can then be bound to a variable as shown
in the RHS actions of the following rule.
(CLIPS> (clear)
(initial-fact)
=>
(printout t
CLIPS> (reset)
CLIPS> (run)
happy-bachelor-mv (Dopey)
none ()
CLIPS>
Just like other languages, CLIPS allows you to define your own functions with
deffunction. The deffunction is known globally, which saves you the effort of entering
the same actions over and over again.
Deffunctions also help in readability. You can call a deffunction just like any other
function. A deffunction may also be used as the argument of another function. A
(printout) can be used anywhere in a deffunction even if it's not the last action because
printing is a side-effect of calling the (printout) function.
<action2> ;action1 to
The ?arg are dummy arguments, which mean that the names of the arguments will not
conflict with variable names in a rule if they are the same. The term dummy argument
is sometimes called a parameter in other books.
Although each action may have returned values from function calls within the action,
these are blocked by the deffunction from being returned to the user. The deffunction
will only return the value of the last action, <actionK>. This action may be a function,
a variable, or a constant.
<Fact-0>
CLIPS> (run)
Hypotenuse=5.0
CLIPS>
Deffunctions may be used with multifield values, as the following example shows.
CLIPS> (clear)
(length $?arg))
CLIPS>
Other Features
Other useful functions follow. For more information, see the CLIPS Reference
Manual.
Function Meaning
round Round toward closest integer. If exactly between two integers, rounds toward
negative infinity.
Up to this point, you've been learning the basic syntax of CLIPS. Now you'll see how
to apply the syntax you've learned to more powerful and complex programs. You'll
also learn some new syntax for input, and see how to compare values and generate
loops.
Besides matching a pattern, a rule can get information in another way. CLIPS can read
the information that you type from the keyboard using the read function.
The following example shows how (read) is used to input data. Note that no extra
(crlf) is needed after the (read) to put the cursor on a new line. The (read)
automatically resets the cursor to a new line.
CLIPS> (clear)
=>
CLIPS>
(defrule check-input
=>
(retract ?color)
CLIPS> (reset)
CLIPS> (run)
red
Correct
CLIPS> (reset)
CLIPS> (run)
green
CLIPS> ; No "correct"
The rule is designed to use keyboard input on the RHS, so it's convenient to trigger
the rule with (initial-fact). Otherwise, you'd have to make up some dummy fact to
trigger the rule.
The (read) function is not a general-purpose function that will read anything you type
on the keyboard. One limitation is that (read) will read only one field. So if you try to
read
primary color is red
only the first field, "primary", will be read. To (read) all the input, you must enclose
the input within double quotes. Of course, once the input is within double quotes, it is
a single literal field. You can then access the substrings "primary", "color", "is", and
"red" with the strexplode or sub-string functions.
The second limitation of (read) is that you can't input parentheses unless they are
within double quotes. Just as you can't assert a fact containing parentheses, you can't
(read) parentheses directly except as literals.
The readline function is used to read multiple values until terminated by a carriage
return. This function reads in data as a string. In order to assert the (readline) data, an
(assert- string) function is used to assert the nonstring fact, just as input by (readline).
A top-level example of (assert-string) follows.
CLIPS> (clear)
<Fact-0>
CLIPS> (facts)
CLIPS>
Notice that the argument of (assert-string) must be a string The following shows how
to assert a fact of multiple fields from (readline).
CLIPS> (clear)
(initial-fact)
=>
CLIPS> (reset)
CLIPS> (run)
Enter input
CLIPS> (facts)
f-0 (initial-fact)
CLIPS>
Since (assert-string) requires parentheses around the string to be asserted, the (str- cat)
function is used to put them around ?string.
Both (read) and (readline) also can be used to read information from a file by
specifying the logical name of the file as the argument. For more information, see
the CLIPS Reference Manual.
Being Efficient
It is very difficult to give precise rules that will always improve the efficiency of a
program running under the Rete Algorithm. However, the following should be taken
as general guidelines that may help:
1. Put the most specific patterns in a rule first. Patterns with unbound variables and
wildcards should be lower down in the list of rule patterns. A control fact should be
put first in the patterns.
2. Patterns with fewer matching facts should go first to minimize partial matches.
3. Patterns that are often retracted and asserted, volatile patterns, should be put last in
the list of patterns.
As you can see, these guidelines are potentially contradictory. A non-specific pattern
may have few matches (see guidelines 1 and 2). Where should it go? The overall
guideline is to minimize changes of the partial matches from one cycle of the
Inference Engine to the next. This may require much effort by the programmer in
watching partial matches. An alternative solution is simply to buy a faster computer,
or an accelerator board. This is becoming more attractive since the price of hardware
always goes down while the price of human labor always goes up. Because CLIPS is
designed for portability, any code developed on one machine should work on another.
Other Features
The test conditional element provides a very powerful way by which to compare
numbers, variables, and strings on the LHS. The (test) is used as a pattern on the LHS.
A rule will only be triggered if the (test) is satisfied together with other patterns.
Many predefined functions are provided by CLIPS as shown in the following table.
Predefined Functions
Logical Arithmetic
or Boolean or + addition
- subtraction
Comparison
All the comparison functions except "eq" and "neq" will give an error message if they
are used to compare a number and non-number. If the type is not known in advance,
the "eq" and "neq" functions should be used. The eq function checks for the same
magnitude and type of its arguments while the "=" function only checks the
magnitude of its (numeric) arguments and doesn't care if they're integer or floating-
point.
The logical functions of CLIPS are and, or, and not. They can be used in expressions
as Boolean functions. In CLIPS, true and false are represented by the symbols TRUE
and FALSE. Note that upper-case must be used for logical values in CLIPS.
In addition to all the predefined functions, you may write external functions or user-
defined functions in C, Ada, or other procedural languages and link to CLIPS. These
external functions are then used as you would any predefined function.
CLIPS also gives you the capability of specifying an explicit and conditional element,
an or conditional element, and a not conditional element on the LHS. Th e absence of
a fact is specified as a pattern on the LHS using the "not" conditional element.
While people can do this fairly easily (practice makes perfect), it's difficult for
computers because they don't normally know which pattern entities are logically
dependent on other pattern entities. CLIPS has a feature to support truth maintenance
which will internally tag those pattern entities which are logically dependent on
others. If these other pattern entities are retracted, CLIPS will automatically retract the
logically dependent ones. The logical conditional element uses the keyword logical
around a pattern to indicate that the matching pattern entities provide logical support
to the assertions on the RHS.
Although the logical support works for assertions, it does not reassert retracted facts.
The moral is, if you lose something due to erroneous information, you can't get it back
(like losing money on your stockbrokers advice.)
CLIPS has two functions to help with logical support. The dependencies function lists
the partial matches from which a pattern entity receives logical support, or none if
there is no support. The second logic function is dependents which lists all pattern
entities which receive logical support from a pattern entity.
The connective constraint, uses "&", "|", or "~". Another type of field constraint is
called a predicate constraint and is often used for pattern matching of more complex
fields. The purpose of a predicate constraint is to constrain a field depending on the
result of a Boolean expression. If the Boolean returns FALSE, the constraint is not
satisfied and the pattern matching fails. You'll find that the predicate constraint is very
useful with numeric patterns.
A predicate function is one which returns a FALSE or a non-FALSE value. The colon
"" followed by a predicate function is called a predicate constraint. The ":" may be
preceded by "&", "|", or "~" or may stand by itself as in the pattern (fact :(> 2 1)). It is
typically used with the & connective constraint as "&"
There are often cases in which it's convenient to have values which are globally
known in an expert system. For example, it is inefficient to have to redefine universal
constants such as [[pi]]. CLIPS provides the defglobal construct so that values may be
universally known to all rules.
Another type of useful function is random numbers. CLIPS has a random function
which returns a "random" integer value. The random number function of CLIPS
actually returns pseudorandom numbers, which means they are not truly random but
are generated by a mathematical formula. For most purposes the pseudorandom
numbers will be fine. Note that the random function of CLIPS uses the ANSI C
library function rand which may not be available on all computers that do not adhere
to this standard. For more information on all these topics, please see the CLIPS
Reference Manual.
Salience is set using a numeric value ranging from the smallest value of - 10000 to the
highest of 10000. If a rule has no salience explicitly assigned by the programmer,
CLIPS assumes a salience of zero. Notice that a salience of zero is midway between
the largest and smallest salience values. A salience of zero does not mean that the rule
has no salience but, rather, that it has an intermediate priority level.
CLIPS provides some procedural programming structures that can be used on the
RHS. These structures are the while and if then else that also are found in modern
high-level languages such as Ada, C, and Pascal.
Another useful function with (while) loops is the break which ends the currently
executing (while) loop. The return function immediately ends the currently executing
deffunction, generic function, method, or message-handler.
Any function may be called from the RHS, which greatly contributes to the power of
CLIPS. Many other CLIPS functions are available that may return with numbers,
symbols, or strings. These functions may be used for their return values or for their
side-effects. An example of a function only used for its side-effect is (printout). The
value returned by the (printout) is meaningless. The importance of (printout) is in its
side-effect of output. In general, functions may have nested arguments if appropriate
to your desired effect.
Before a file can be accessed for reading or writing, it must be opened using the open
function. The number of files that can be opened at once is dependent on your
operating system and hardware. When you no longer need to access a file, you should
close it with the close function. Unless a file is closed, there is no guarantee that the
information written to it will be saved.
The logical name of a file is how CLIPS identifies the file. The logical name is a
global name by which CLIPS knows this file in all rules. Although the logical name
could be identical to the filename, you may want to use something different. Another
advantage of a logical name is that you can easily substitute a different filename
without making major program changes.
The function to read data from a file is the familiar (read) or (readline). The only new
thing that you have to do is to specify the logical name from which to read as the
argument of (read) or (readline).
To (read) more than one field, you must use a loop. Even with (readline), a loop is
necessary to read multiple lines. A loop can be written by having one rule trigger
another or with a while-loop. The loop should not try to read past the end of file or the
operating system will issue an error message. To help prevent this, CLIPS returns an
EOF symbolic field if you try to read past the end of file (EOF).
The evaluation function, eval, is used for evaluating any string or symbol except the
"def" type constructs such as defrule, deffacts, etc., as if entered at the top- level. The
build function takes care of the "def" type constructs. The (build) function is the
complement of (eval). The build function evaluates a string or symbol as if it were
entered at the top-level and returns TRUE if the argument is a legal def-type construct
such as (defrule), (deffacts), and so forth.
How to be Objective
The term paradigm comes from the Greek word paradeigma which means a model,
example, or pattern. In computer science, a paradigm is a consistent, organized
methodology for trying to solve a problem. Today, there are many programming
paradigms such as OOP, procedural, rule-based, and connectionist. The term artificial
neural systems, is a modern synonym for the older term connectionist.
CLIPS provides three paradigms: rules, objects, and procedures. You will learn more
about the objects in the CLIPS ObjectOriented Language (COOL) which is integrated
with the rule and procedural based paradigms of CLIPS. CLIPS supports the
procedural paradigm through generic functions, deffunctions, and user-defined
external functions. Depending on the application, you can use rules, objects,
procedures, or a combination.
Rather than imposing a single paradigm on the user, our philosophy is that a variety of
specialized tools, a multiparadigm approach, is better than trying to force everyone to
use a single general purpose tool. As an analogy, while you could use a hammer and
nails for fastening everything, there are cases in which other fasteners are preferred.
For example, imagine fastening your pants with a hammer and nails instead of a
zipper. (NOTE: if anyone does use a hammer and nails on their pants, please contact
the Guiness Book of World Records.)
In this chapter you'll learn more about classes and objects called instances. You will
see how to specify the attributes of classes using slots and how to send messages to
objects.
The Birds and the BeesIn Chapter 1 you learned the basic ideas of inheritance. The
reason that inheritance is so important in OOP is that inheritance allows the easy
construction of customized software. By customized software, we don't mean that the
software is built from scratch. Rather, it's more like taking a mass produced item and
modifying it for a special application. The mass produced item can be considered a
product of a software factory that quickly, economically, and reliably produces items
of a general type that are meant to be easily customized.
The heart of the OOP paradigm is the creation of a class hierarchy to quickly, easily,
and reliably produce software. Generally, this software is a modification of existing
software so that programmers are not always "reinventing the loop."
Although in the past, people have tried to provide reusable code through such
mechanisms as subroutine libraries, the pure OOP paradigm in languages such as
Smalltalk carries the concept of reusable code to its logical conclusion by trying to
build all the software in a system as reusable code. In Smalltalk, everything is an
object, even the classes. In CLIPS, instances of the primitive types such as NUMBER,
SYMBOL, STRING and so forth, as well as user-defined instances are objects.
Classes are not objects in CLIPS. For example, the NUMBER 1, the SYMBOL Duck,
the STRING "Duck", and the user-defined instance Duck are all objects.
The OOP paradigm is quite different from the subroutine library approach in which
bits and pieces of subroutine code may or may not be used depending on the
programmer's whim. The OOP paradigm encourages and supports modular code-- the
message-handlers-- that can be easily modified and maintained. This feature of code
maintainability is playing an increasingly important role as the size and cost of
systems increase.
A class in OOP is like a software factory which has the design information about an
object. In other words, a class is like a template which can be used to produce
identical objects that are the instances of the class. The classic analogy is that a class
is like the blueprint of a cow, and the object that produces milk, such as Elsie, is the
instance.
The general syntax of an instance name is simply a symbol surrounded by brackets,
[ ], as follows.
[<name>]
The brackets are not actually part of the instance name, which is a symbol, like Elsie.
Brackets are used to surround an instance name if there is danger of ambiguity in
using the name. This may occur in the (send) function and so brackets are used in a
(send). In case of doubt, use brackets, since it doesn't hurt.
Some of the different types of objects in CLIPS are indicated in the following table.
Object Class
Dorky_Duck SYMBOL
"Dorky_Duck" STRING
1.0 FLOAT
1 INTEGER
[Dorky_Duck] DUCK
The classes of SYMBOL, STRING, FLOAT, INTEGER, and MULTIFIELD have the
same names as those you are familiar with from rule-based programming in CLIPS.
These are called primitive object types because they are provided by CLIPS and
automatically maintained as needed. These primitive types are mainly provided for
use in generic functions. Two compound classes are NUMBER which is FLOAT or
INTEGER, and LEXEME which is SYMBOL or STRING. The compound classes are
provided for convenience if the type of number, or type of characters doesn't matter.
In contrast, userdefined object types are those that you define through user- defined
classes. If you refer back to the predefined CLIPS classes of Fig. 1.7 in chapter 1,
you'll see that primitive and user- defined classes are the top- level division of classes
in CLIPS.
Two functions convert a symbol to an instance name, and vice versa. The
symboltoinstancename converts a symbol to an instance name, as shown by the
following.
CLIPS> (clear) ; Get rid of any old classes
[Dorky_Duck]
[Dorky_Duck]
CLIPS>
Notice how standard CLIPS functions such as (sym- cat), which concatenates items,
can be used with the object system of CLIPS.
Dorky_Duck
"Dorky_Duck is a DUCK"
CLIPS>
Dorky DuckThere is a difference between Nature and OOP. In Nature, objects are
reproduced only from like objects, like the birds and the bees (the chicken and the egg
are the exceptions to this rule.) However, in OOP instances are only created using the
class template. In a pure OOP like Smalltalk, an instance of a specific class is created
by sending the class a message. In fact, the heart of OOP involves sending different
types of messages from one object to another, even from an object to itself.
In order to see how messages work, let's start by entering the following commands to
create a user- defined DUCK class and check that it's entered. Notice that the role
concrete descriptor is specified in order to allow direct instances of DUCK to be
created. If the role is unspecified, CLIPS determines the role by inheritance.
If a class has role abstract no direct instances of it can be made. Abstract classes are
defined for inheritance purposes only. For example, an abstract class called PERSON
could be defined whose properties such as name, address, age, height, weight, and so
on are inherited by concrete classes MAN and WOMAN. A direct instance of MAN
could be a man-person called Harold, and a direct instance of WOMAN is a woman-
person called Henrietta.
CLIPS> (defclass DUCK (is-a USER) (role concrete))
==================================================================************
******************************************************Concrete: direct
instances of this class can be created.
Direct Subclasses:
------------------------------------------------------------------------------
--
Recognized message-handlers:
CLIPS>
******************************************************************============
======================================================CLIPS>
Since classes are not objects in CLIPS, we can't send a message to make an object.
Instead, the make-instance function is used to make an instance object. The basic
syntax is as follows.
(make-instance [<instance-name>] of <class> <slot-override>)
Now that we have a duck factory, let's make some instances as follows, where the
name of the instance is in brackets. Note the use of the "of" keyword to separate the
instance name from the class name. You must include the "of" or a syntax error will
result. Also, note that the brackets in the code mean an instance name, while brackets
in the metasyntax such as for (make-instance) above, mean option.
CLIPS> (make-instance [Dorky] of DUCK)
[Dorky]
[Dorky_Duck]
CLIPS> (instances)
[Dorky] of DUCK
[Dorky_Duck] of DUCK
CLIPS>
After the instance is successfully created, CLIPS responds with the name of the
instance. If it is not possible to create an instance, CLIPS responds with a FALSE.
Also, like the (rules) and (facts) commands, CLIPS has an instances function to print
out the instances of a class.
For the case of (make-instance), the brackets around the instance name is optional for
a USER-defined class. As an example, let's create Dorky's cousin, Dorky_Duck,
without brackets as follows.
CLIPS> (make-instance Dorky_Duck of DUCK)
CLIPS>
There are two important rules about instances to keep in mind.
For example, let's make a clone of Dorky_Duck as follows (It's this evil clone that
always gets Dorky_Duck in trouble because no one can tell them apart. Kids often
have clones like this too, and some adults.)
CLIPS> (make-instance Dorky_Duck of DUCK)
[Dorky_Duck]
CLIPS> (instances)
[Dorky] of DUCK
CLIPS>
Much Ado About InstancesIf a (reset) command is issued, all the instances in memory
are deleted and an instance [initial-instance] is created, analogous to the fact, initial-
fact.
CLIPS> (reset)
CLIPS> (instances)
[initial-object] of INITIAL-OBJECT
CLIPS>
Just as (deffacts) defines facts, there is also a definstances to define instances when a
(reset) is issued. The following (definstances) also illustrates the optional comment in
double quotes after the instance name, DORKY_OBJECTS.
CLIPS> (definstances DORKY_OBJECTS "The Dorky Cousins"
(Dorky of DUCK)
(Dorky_Duck of DUCK))
CLIPS> (instances)
[initial-object] of INITIAL-OBJECT
CLIPS> (reset)
CLIPS> (instances)
[initial-object] of INITIAL-OBJECT
[Dorky] of DUCK
[Dorky_Duck] of DUCK
CLIPS>
The Disappearing DuckAlthough a (reset) will delete all instances except [initial-
instance], it will also make new instances from (definstances). If you want to
permanently delete an instance, the function unmakeinstance will delete one or all
instances, depending on its argument. To delete all instances, use the "*".
TRUE
(Dorky of DUCK)
(Dorky_Duck of DUCK))
[initial-object] of INITIAL-OBJECT
[Dorky] of DUCK
[Dorky_Duck] of DUCK
TRUE
CLIPS> (instances)
[initial-object] of INITIAL-OBJECT
[Dorky_Duck] of DUCK
CLIPS>
Another way to delete a specific instance is to send a delete message. The general
syntax of the (send) function is as follows.
(send [<instance-name>] <message>)
_Only one instance name can be specified in a command and it must be surrounded
by brackets if it is a user-defined name.
[initial-object] of INITIAL-OBJECT
[Dorky] of DUCK
[Dorky_Duck] of DUCK
TRUE
CLIPS> (instances)
[initial-object] of INITIAL-OBJECT
[Dorky] of DUCK
For a total of 2 instances.
CLIPS>
The "*" in a (send) will not work to delete all instances. The "*" only works with the
(unmake) function. Another alternative is to define your own handler for delete that
will accept the "*" and thus allow you to (send [instance-name] my_delete *)
messages.
A (send) message is acted upon only by a target object which has an appropriate
handler. CLIPS automatically provides handlers for print, init, delete and so on for
each user-defined class. It's important to realize that the message (send [Dorky_Duck]
delete) works only because this instance is a user-defined class. If you define classes
which do not inherit from USER such as a subclass of INTEGER, you must also
create appropriate handlers to carry out all desired tasks such as printing, creating, and
deleting instances. It's much easier to define subclasses of USER and take advantage
of system-supplied handlers.
What Did You Have For BreakfastThe (send) function is the heart of OOP operation
since it is the only proper way for objects to communicate. According to the principle
of object encapsulation, one object should only be allowed to access another object's
data by sending a message.
For example, if someone wants to know what you had for breakfast, they'll generally
ask you, i.e., send a message. An impolite alternative would be to yank open your
mouth and peer down your throat. If the principle of object encapsulation is not
followed, any object can fool around with the private parts of other objects, with
potentially disastrous results.
One useful application of (send) is to print information about an object. So far all the
examples of objects that you have seen have no structure. However, just as
deftemplate gives structure to a rule pattern, the slots give an object structure. For
both deftemplate and objects, a slot is a named location in which data can be stored.
However, unlike deftemplate slots, objects obtain their slots from classes, and classes
use inheritance. Thus, the information in object slots can be effectively inherited by
objects of subclasses. An unbound slot is one that has no values assigned. All
slots must be bound.
As a simple example, let's make an object with slots to hold personal information and
then send messages to it. The following commands will first set up the CLIPS
environment with the appropriate constructs. The slots named sound and age initially
contain no data, i.e., nil values.
CLIPS> (clear)
(Dorky_Duck of DUCK))
CLIPS> (reset)
[Dorky_Duck] of DUCK
(sound nil)
(age nil)
quack
[Dorky_Duck] of DUCK
(sound quack)
(age nil)
CLIPS>
Notice that the slots are printed in the order defined in the class. However, if the
instance inherits slots from more than one class, the slots from the more general
classes will be printed first.
Just as slots describe instances, facets describe slots. A special facet is needed in this
example, createaccessor, which tells CLIPS to create put- and get- handlers for the
class. If you define your own handlers, then you won't use the create-accessor facet.
The facet types for create accessor are read- write, read, and write. Facets are
described in more detail in the next chapter.
Whether you use the handlers created by CLIPS or else define your own, you can also
set the slot access to read-write, read-only, and initialize-only. The read-write access
is the default and so it was not necessary to specify it in this example.
The value of a slot is changed using the put- message. Notice the dash, "-", at the end
of "put-". The dash is an essential part of the message syntax since it separates the
"put" from the slot name. Only one "put-" is allowed in a (send). Thus, to change
multiple slots or the same slot of many instances, you must send multiple messages.
Instead of doing this manually, it's possible to write a function to do multiple sends, or
use the modify-instance function.
[Dixie_Duck]
[Dixie_Duck] of DUCK
(sound quack)
(age 2)
CLIPS>
The complementary message to "put-" is get- which gets the data from a slot, as
shown in the following example. If a put- is successful it returns the new value, while
if get- is successful it returns the appropriate data. If the put- or get- does not succeed,
an error message will be returned. The following examples show how this works.
CLIPS> (send [Dorky_Duck] put-color white) ; No slot color
FALSE
nil
CLIPS>
In contrast to the put- message, the get- message returns the value of a slot. Since the
value of get- is returned, it can be used by another function, assigned to a variable,
and so forth. In contrast, a value that is printed out cannot be used by another
function, assigned to a variable, and so forth because the value goes to the standard
output device. One way of getting around this problem is to print out to a file and then
read in the data from the file. While this is not an elegant solution, it does work.
Another way is to write your own print message-handler that also returns values.
A very important point about slots is that you cannot modify the slots of a class by
adding slots, deleting slots, or changing the characteristics of slots. The only way to
change a class is to (1) delete all instances of the class, and (2) use a (defclass) with
the same class name and the desired slots. This situation is analogous to modifying a
rule by loading in a new rule with the same name.
Class EtiquetteNow that you've learned aqbout slots and instances, it's time to discuss
class etiquette. The term etiquette refers to a set of guidelines for doing something.
The first rule discourages the creation of a single class for your application. If a single
class is adequate, then you probably don't need OOP. By creating classes in
increments, you can more easily verify, validate, and maintain your code. In addition,
incremental class hierarchies can be easily put in class libraries to greatly facilitate the
creation of new code. This concept of class libraries is analogous to subroutine
libraries for actions. Only is-a links can be used since this is the only relationship that
Version 6.0 of CLIPS supports.
The second rule encourages the idea that classes are intended as a template to produce
multiple objects of the same kind. Of course you can start out with zero or one
instance. However, if you'll never need more than one instance in a class, you should
consider modifying its superclass to accomodate the instance rather than defining a
new subclass. If all your classes only have one instance, it is probable that your
application is simply not well-suited to OOP and that coding in a procedural language
may be best.
The third rule means that classes should not be named after instances and vice versa,
to eliminate confusion.
Other FeaturesThere are a number of useful predicate functions for slots. If you use
these predicate functions to test for appropriate values to functions, your program will
be more robust against crashes. In general, if a function does not return TRUE, it
returns FALSE.
Function Meaning
In this chapter you'll learn more about slots and how to specify their characteristics by
using facets. The use of facets is good software engineering because there is a greater
chance of CLIPS flagging an illegal value rather than risking a runtime error or crash.
There are many types of facets that may be used to specify slots, as summarized in the
following table.
For reasons of space, we'll only describe a few facets in more detail in the rest of this
chapter. For more details, see the CLIPS Reference Manual.
A Slot Named DefaultThe default facet sets the default value of a slot when an
instance is created or initialized, as shown in the following example.
CLIPS> (clear)
[Dorky_Duck]
[Dorky_Duck] of DUCK
(sound quack)
(ID nil)
(sex male)
CLIPS>
As you can see, the default values for slot sex and slot sound were set by the default
facet values. Following the default keyword can be any valid CLIPS expression that
does not involve a variable. For example, the default expression of the sound slot is
the symbol quack. Functions may be used in the facet expression as will be shown in
the next example.
This default facet is a static default because the value of its facet expression is
determined when the class is defined and never changed unless the class is redefined.
For example, let's set the default value of slot ID to the (gensym*) function which
returns a new value not in the system everytime it's called.
CLIPS> (clear)
[Dorky_Duck]
(sound quack)
(ID gen1)
(sex male)
[Dorky_Duck]
[Dorky_Duck] of DUCK
(sound quack)
(ID gen1)
(sex male)
CLIPS>
As you can see, the ID is always gen1 since (gensym*) is only evaluated once, and not
again when the second instance is created. Note that the (gensym*) values may be
different on your computer if you have already called the (gensym*) since it
increments by one each time it is called, and is not reset by a (clear). The (gensym*)
function is reset to its starting value only if you restart CLIPS.
Now suppose that we want to keep track of the different Dorky_Duck instances that
have been created. Rather than using the static default, we can use the facet called
default dynamic which will evaluate its facet expression every time a new instance is
created. Notice the difference between the following example and the previous.
CLIPS> (clear)
(default-dynamic (gensym*)))
[Dorky_Duck] of DUCK
(sound quack)
(ID gen2)
(sex male)
[Dorky_Duck]
[Dorky_Duck] of DUCK
(sound quack)
(sex male)
CLIPS>
In this example which uses dynamic default, the ID of the second instance, gen3, is
different from the first instance, gen2. In contrast, for the previous example of static
default, the ID values were the same, gen1, since the (gensym*) was only evaluated
once when the class was defined rather then for every new instance in the case of
dynamic default.
Cardinal PropertiesThe cardinality of a slot refers to one of two types of fields that a
slot can hold: (1) single-field, or (2) multifield. The term cardinality refers to a count.
A bound single- field slot contains only one field, while a bound multifield slot may
contain zero or more fields. The bound single-field slot and the bound multifield slot
each contain one value. However, the one multifield value may have multiple fields in
it. For example, (a b c) is a single multifield value with three fields. The empty string
"" is a single-field value, just as "a b c" is. In contrast, an unbound slot has no value.
A multiple facet with keyword multislot, is used to store a multifield value as shown
in the following example.
CLIPS> (clear)
[Dorky_Duck]
[Dorky_Duck] of DUCK
CLIPS>
A multifield value can be accessed using get- and put- as shown in the following
examples, which shows how to keep track of quacks.
CLIPS> (send [Dorky_Duck] put-sound quack1 quack2 quack3)
CLIPS>
Standard CLIPS functions such as nth$ to get the nth field of a multislot value can be
used. The following example shows how to pick a certain quack.
CLIPS> (nth$ 1 (send [Dorky_Duck] get-sound))
quack1
CLIPS> (nth$ 2 (send [Dorky_Duck] get-sound))
quack2
quack3
CLIPS>
Other Features
CLIPS has several multifield slot functions as shown in the following table.
Function Meaning
A multifield slot with no values, e.g., the empty multifield value (), may be assigned
to a slot with a (multiple) facet. Note that there is a difference between a slot with an
empty multifield value () and an unbound slot. If you think of an empty multifield
value as analogous to an empty bus, you can see there is a difference between no
people (unbound slot) and a bus with no people (empty multifield value, () ).
A storage facet defines one of two places that a slot value is stored: (1) in an instance,
or (2) in the class. A slot value stored in the instance is called local because the value
is only known to the instance. Thus, different instances may exist that have different
local slot values. In contrast, a slot value stored in a class is called shared because it is
the same for all instances of the class.
A local value is specified by the local facet, which is the default for a slot. A shared
value is specified by the shared facet and all instances with this slot type will have
their slot value automatically changed if one changes. An access facet defines one of
three types of access for a slot, as summarized in the following table.
Another way to set the instance values is with the initialize-instance function. An
(initialize-instance) can be called at any time to reset the default values and retain
values in non-(default) slots.
Two predicate functions are designed for use with the access facets. Both these
predicate functions return an error message if the specified slot or instance does not
exist. The slot-writablep is a predicate function which returns TRUE if a slot is
writable and FALSE if it is not. The slot-initablep predicate function returns TRUE if
the slot is initializable and FALSE if it is not. The term initializable means that it
is not read-only.
The inherit facet, which is the default, specifies that indirect instances of a class may
inherit this slot from the class. As you recall, the indirect instances of a class are the
instances of its subclasses, while the direct instances are those defined specifically for
the class. The indirect instances of a class are direct instances of the subclasses in
which they are defined. For example, [Dorky_Duck] is a direct instance of DUCK and
an indirect instance of USER which is the superclass of DUCK. The no-inherit facet
specifies that only a direct instance has the class slot.
It's important to realize that the (no-inherit) facet only prohibits inheritance from the
class and not from its superclasses. This means that an instance may still inherit from
superclasses of the (no-inherit) class.
The composite facet. facet states that facets which are not explicitly defined in the
highest precedence class take their facets from the next higher precedence class. If the
facet is not explicitly set in the next higher precedence class and it is composite too,
CLIPS tries the next higher and so on until the facet is defined or there are no more
classes. If the next higher class is not composite, CLIPS does not check further. The
opposite to the composite facet is the exclusive facet, which is the default. For more
information, see the CLIPS Reference Manual.
Handlers are essential in OOP because they support object encapsulation. The only
proper way that objects can respond to messages is by having an appropriate handler
to receive the message and take appropriate action. In this chapter you'll learn the how
messages are interpreted by objects. You'll see how to modify existing message-
handlers, and how to write your own.
Polymorphism is one of the five generally accepted features of a true OOP language.
For example, the same type of message, (send <instance-name> print), may have
different actions depending on the class of the object which receives it. In addition to
egg-of and color, DUCK objects print out sound, ID, and age, while DUCKLING
objects only print out sound and age.
In languages without polymorphism, you would have to define one function, (send-
egg- print) for egg types and another function, (send-duckling-print) for the duckling
type. However, in OOP, no matter how many classes are defined, the same message,
(send <instance-name> print), will print the object slots. This greatly improves the
efficiency of program development since you do not have to define new functions for
every new type.
This extreme use of polymorphism would create a programmer's Tower of Babel and
make it very hard to understand the code since everything would be run-time
dependent. Defining message-handlers of the same name in different classes that do
completely different things goes against the Principle of Least Astonishment.
As you can see from Fig. 1.7 of chapter 1, the class NUMBER has subclasses
INTEGER and FLOAT. Since these are predefined classes, it would seen natural to do
numeric calculations by sending messages to numbers. Let's try it as follows.
CLIPS> (clear)
CLIPS> (send 1 + 2)
FALSE
CLIPS>
Well, as you can see, this example didn't work. The reason why is implied in the error
message. Let's check it out by obtaining more information about the INTEGER class
since that was the target object of the print message.
CLIPS> (describe-class INTEGER)
==================================================================
******************************************************************Abstract:
direct instances of this class cannot be created.
Direct Subclasses:
******************************************************************============
======================================================CLIPS>
The problem is that the INTEGER class has no handler for "+". In fact, it has no
handlers at all since none are listed. As you recall, the USER class and its subclasses
always have print, delete, and other handlers automatically defined by CLIPS. If we
want to send print messages to an object like 1 of the INTEGER class, we'll have to
make our own print handler.
Before writing this handler, let's answer a question that you may have concerning how
INTEGER can have instances. Since INTEGER is an abstract class, you may wonder
how it can have instances such as 1, 2, 3, etc. Although you cannot make direct
instances of an abstract class, you can make use of existing instances. For the case of
the predefined system class INTEGER, all the integers up to the maximum allowed
are available as objects. Likewise, strings and symbols are available for the system
defined abstract classes STRING and SYMBOL, and so forth for the other predefined
classes.
Shown following is the definition of a handler for the NUMBER class that will handle
addition by messages. The handler is defined for NUMBER rather than INTEGER
because we would also like to handle FLOAT objects too. Instead of defining the
same handler for FLOAT and for INTEGER, it's easier to just define a handler for the
superclass NUMBER. If a handler for a message is not defined in the class of the
object, CLIPS tries all the handlers in the inheritance precedence list. Since "+" is not
defined for INTEGER, CLIPS tries NUMBER next, finds the applicable handler, and
returns the result of 3.
CLIPS> (defmessage-handler NUMBER + (?arg) ; Argument of handler
CLIPS> (send 1 + 2)
5.5
5.1
==================================================================************
******************************************************Abstract: direct
instances of this class cannot be created.
------------------------------------------------------------------Recognized
message-handlers:
The variable ?self is a special variable in which CLIPS stores the active instance.
The ?self is a reserved word that cannot be explicitly included in a handler argument,
nor can it be bound to a different value. The active instance is the instance to which
the message was sent. In our example, all the predefined classes such as NUMBER,
INTEGER, and FLOAT are all subclasses of the PRIMITIVE class. This is in contrast
to USER, which is the other main subclass of OBJECT.
CLIPS>
Notice that the handler is defined for the LEXEME class since that is a superclass of
both SYMBOL and STRING. In this case, the handler returns a SYMBOL since
(sym- cat) is used.
This example also illustrates why brackets may be necessary in a (send). As shown in
this example, the message goes to the SYMBOL Dorky_ without brackets. With
brackets, the message goes to an object [Dorky_] of a user-defined class. Here we
assume that [Dorky_] could be an object of a user-defined class, such as DUCK.
The real utility of handlers is with subclasses of USER since you can define instances
of these classes. To see how handlers work in this case, let's first set up the
environment as follows.
(clear)
(definstances DUCKY_OBJECTS
(reset)
As a simple example, let's write a handler that will print out the slots of the active
instance. We can make use of the ppinstance function to print out the slots of the
active instance. This function does not return a value and is used only for its side-
effect of printing to the standard device. Also, it can only be used from within a
handler since only there is the active instance known. Shown following is a USER-
defined handler called print- slots that prints out the slots of the active instance using
(ppinstance).
CLIPS> (defmessage-handler USER print-slots ()
(ppinstance))
[Dorky_Duck] of DUCK
(age 2)
(sound quack)
CLIPS>
Although the handler could be defined just for DUCK in this case, a handler defined
for USER will be called for all subclasses of USER, not just DUCKLING and DUCK.
Thus, the handler print-slots will work for all subclasses that we may define of USER.
Of course it's possible to get carried away and define all your message handlers as
USER handlers. However, it's good style and improves efficiency to define handlers
as close as possible to the class or classes for which they are intended. Efficiency is
improved because CLIPS does not have to keep searching through a lot of classes to
find the applicable handler.
Getting Around
Let's examine message-handlers in more detail now. We'll define a handler to print
out a header when an object receives a message to print itself. The message-handler is
defined using a defmessage-handler construct as follows.
CLIPS> (defmessage-handler USER print before ()
[Dorky_Duck] of DUCK
(age 2)
(sound quack)
CLIPS>
The reason that a header is printed rather than a trailer at the end has to do with the
handler type. A before type handler is used before the print message. To make a
trailer, use the after type handler as shown in the following example.
CLIPS> (defmessage-handler USER print after ()
[Dorky_Duck] of DUCK
(age 2)
(sound quack)
CLIPS>
(<parameters>* [wildcard-parameter])
<action>*)
While there may be multiple actions in a handler, only the value of the last action is
returned. Notice that this is just like a (deffunction).
The empty parentheses () that follow the before handler type mean that there are
neither parameters nor a wildcard parameter. In other words, the header handler takes
no arguments and so the parentheses are empty, but required. Note that while multiple
parameters may be used, there can be only one wildcard.
Primary Considerations
As you can see, the trailer handler is the same as the header handler except that
an after handler type is used, and the action text is different. Thus, a before handler
type does its task before the primary type handler, and an after handler does its task
after the primary handler. A primary is intended to do the major task. An around
handler type is intended to set up the environment for the rest of the handlers. The
before and after types are intended for minor tasks such as initializing variables or
printing, while the primary does the major task.
around Set up environment for other handlers Yes before Auxilliary work before
primary No
primary Perform major task of message Yes
after Auxilliary work after primary No
The handler types are listed in the order that they are normally called during execution
of a message. Depending on the handler type, CLIPS knows when to execute it. That
is, an around handler starts before any before handlers. A before handler is executed
before any primary handlers, which are followed by the after handlers. The exception
to this sequential handler execution is the around type handler. If an around handler is
defined, it will start execution before any of the others, perform specified actions, and
then complete its actions after all the other handler types have finished. You'll see a
detailed example of these handlers execution soon.
The class role describes the intended purpose of each type. The column headed
"Return Value" describes whether the handler type is generally intended for a return
value or simply to provide a useful side-effect such as printing. This consideration
will depend on the handler. For example, many user-defined primary handlers may be
written to return a value as the result of some numeric calculation or string operation.
An exception to returning a useful return value is a print primary handler whose main
task is the side-effect of printing, and does not have a return value.
The following table lists the predefined primary handlers of USER. By inheritance,
these are available for all subclasses of USER.
These primary handlers are predefined and cannot be modified unless you change the
source code of CLIPS. However, you may define the before, after and around handler
types for these primaries. You've already seen an example of changing the before and
after handler types for the USER print handler. Now let's look at some examples of
defining the before and after handler types for the init primary handler.
CLIPS> (defmessage-handler USER init before ()
CLIPS> (reset)
[Dixie_Duck]
CLIPS> (instances)
[initial-object] of INITIAL-OBJECT
[Dorky_Duck] of DUCK
[Dinky_Duck] of DUCKLING
[Dixie_Duck] of DUCK
CLIPS>
The self parameter is useful because it can be used to read a slot value in the form
?self:<slot-name>
However, it cannot be used to write a slot value. The "?self:" notation is more
efficient than sending messages but can only be used from within a handler on its
active instance. In contrast, the dynamic-get- and dynamic-put- functions can be used
from within a handler to read and write a slot value of the active instance. Although
you can use messages from inside a handler, such as the following, it's not efficient.
(send ?self dynamic-get-<slot>)
Age = 2
CLIPS>
The ?self:age can only be used in a class and its subclasses which inherit the slot age.
The ?self:<slot-name> is evaluated in a static way through inheritance. This means
that if a subclass redefines a slot, a superclass message-handler will fail if it tries to
directly access the slot using ?self:<slot-name>.
Age = 2
CLIPS>
As an example of using a dynamic-put- function in a handler, suppose we want to help
Dorky_Duck regain some of his youth. The following example shows how his age can
be changed using a handler. This example also illustrates how a value can be passed to
a handler through the ?change variable.
CLIPS> (clear)
[Dorky_Duck]
I am only 1
CLIPS>
As you can see, Dorky_Duck's belief is so strong that the changed age is put in his age
slot. Notice how the handler uses the variable ?new-age to store the changed age,
which is then put into the age slot of the instance.
A daemon is a handler which executes whenever some basic action like initialization,
deletion, get, or put is performed on an instance. A rule cannot be considered a
daemon because it's not certain that it will be executed just because its LHS patterns
are satisfied. The only thing that is certain is that a rule will become activated when
its LHS is satisfied -- not that it will execute.
There is no explicit keyword for daemon since it's just a concept. The before and after
handlers that printed strings can be considered print daemons. These handlers waited
for a (send [Dorky_Duck] print-age) message to trigger their action. First the before
handler printed its string, then the primary handler printed, and finally the after
handler printed. One daemon is the before handler which waits for a print message.
The second daemon is the after handler that waits for the print primary to finish
printing.
Printing is not considered a basic action because there is no return value associated
with a (send <instance> print). The print message is only sent for the side- effect of
printing. In contrast, a (send <instance> get-<slot>) message will return a value that
may be used by other code. Likewise, the initialization, deletion, and put all have an
effect on an instance and so are considered basic actions like get.
Daemons are easily implemented using before and after handlers since these will be
executed before and after their primary handler. Implementing daemons like this is
called declarative implementation because no explicit actions on the part of the
handler is necessary for it to be executed. That is, CLIPS will always execute a before
handler before its primary and will always execute an after handler after its primary.
In a declarative daemon implementation, the normal operation of CLIPS will cause
the daemons to be activated when their time has come. Thus, the declarative
implementation is implicit in the normal operation.
2. Call the next handler using either call-next-handler to pass the same arguments or
overridenexthandler to pass different ones.
4. After any other around, before, primary, or after handlers finish, the around handler
resumes execution.
The keyword call-next-handler is used to call the next handler(s). A handler is said to
be shadowed by a shadower if it must be called from the shadower by a function such
as call-next-handler. The call- next- handler may be used multiple times to call the
same handler(s).
A predicate function called next-handlerp is used to test for the existence of a handler
before the call is made. If no handler exists, then next-handlerp will return FALSE.
The following example illustrates the around handler through a truthful daemon that
tells on Dorky_Duck whenever he lies about his age.
CLIPS> (defmessage-handler DUCK lie-about-age around (?change)
(call-next-handler))
[Dorky_Duck]
I am only 2
Dorky_Duck is lying!
Dorky_Duck is lying!
He's really 3
CLIPS>
Although Dorky_Duck may still lie about his age, the daemon tells the truth.
Notice the ?change argument. Although the around handler does not use ?change, the
lie-about-age primary that is called by the call-next-handler does need it to change the
age. Thus, ?change must be passed to the primary by the around handler. An error
message will occur if you leave out the ?change.
The call-next-handler always passes the arguments of the shadower to the shadowed
handler. It's possible to pass different arguments to a shadowed handler by use of the
override- next- handler function as shown in the following example.
CLIPS> (defmessage-handler DUCK lie-about-age around (?change)
[Dorky_Duck]
I am only 2.5
Dorky_Duck is lying!
Dorky_Duck is lying!
He's really 3
CLIPS>
_ It's important to keep in mind that the return value of call- next- handler and
override- next- handler is that of the shadowed handlers.
Shown following are the rules of message dispatch. However, note the following
prerequisite to any message handling:
2. The around, before, and primary handlers are called in order of highest
precedence class to lowest.
3. The after handlers are called from lowest precedence class to highest.
4. Each around handler must explicitly call the next shadowed handler.
5. Higher precedence primaries must explicitly call lower precedence (shadowed)
Since only around and primary handlers can return values, and the around shadows
primaries, it follows that the return value of a (send) will be the around return value. If
there is no around, then the return value will be that of the highest precedence
primary. As mentioned before, there must always have at least one applicable
primary handler.
The following table summarizes the return value of the handler types.
around Ignore or capture return value of next most specific around or primary
before Ignore. Side-effect only
primary Ignore or capture return value of more general primary
after Ignore. Side-effect only.
Up to now, we've discussed inheritance using only is-a links. As you've seen, this type
of inheritance relationship is good for defining classes that are more and more
specialized. That is, you start off by defining the most general classes as a subclass of
USER, and then define more specialized classes with more slots in the lower levels of
the class hierarchy.
Normally, you design new classes as specializations of existing ones. This paradigm is
Inheritance by Specialization. As you recall from the quadrilateral example of Fig. 1.8
of chapter 1, the highest level is quadrilateral, and the lower levels are trapezoid,
parallelogram, rectangle, and then square along one inheritance path. Trapezoid is a
special class of quadrilateral, parallelogram is a special class of trapezoid, rectangle is
a special class of parallelogram, and square is a special class of rectangle.
Inheritance can also be used to build up more complex classes. However, this is not
quite as direct in CLIPS. As an example, the basic class for geometry is a POINT
containing a single slot point1. A LINE can be then defined by adding point2 to
POINT. A TRIANGLE is defined by adding point3 to LINE, and so on for
QUADRILATERALS, PENTAGONS, etc.
(defclass POINT (is-a USER)
(multislot point1))
(multislot point2))
(multislot point3))
Notice how each class is a specialization of its parent class by inheriting the
superclass points and then adding one new point.
There is a subtle but important difference between this example of specialization, and
generalization. In specialization, new classes are built up by adding specialized slots
which are the same type as superclass slots. Thus, POINT, LINE, and TRIANGLE all
have point-type slots.
In contrast, generalization builds up using new types of slots defined for each class.
Class POINT has a point-type slot. LINE has two point-type slots. TRIANGLE has
three line-type slots. QUADRILATERAL has four line-type slots, and so on.
Generalization is good for synthesis, which means a building up. The opposite of
synthesis is analysis, which means taking apart or a simplification. The model for
analysis is specialization.
Fig. 10.1 illustrates one inheritance scheme for polygons in which classes are built by
inheritance. In this case, the link between classes would be "is-made-of". Thus, a
LINE is-made-of POINT. A POLYGON is-made-of LINE, and so forth.
(propagation no-inherit)))
CLIPS>
The (no-inherit) facet is used to prevent a LINE from inheriting a position slot.
Instead, a LINE will be defined by two points called slot point1 and slot point2. These
two slots will define the line and it is extraneous to have an additional position slot by
inheritance.
The definition of the LINE class is a little more complex. The reason for the added
complexity is that the details of implementation are included in the (defclass) because
Version 6.0 only supports is-a relationships.
(defclass LINE (is-a POINT)(role concrete)
(slot point1 (create-accessor read-write)
(propagation no-inherit))
(propagation no-inherit))
(message-handler find-point)
(message-handler print-points)
(message-handler find-distance)
(message-handler print-distance))
At this time you may be wondering why POINT and LINE are not both defined as
subclasses of USER since all their slots have (no- inherit) facets. Since all the slots of
POINT, LINE, and the TRIANGLE class to be defined later have (no-inherit) facets,
all these classes could be defined as direct subclasses of USER rather than defining
LINE as a subclass of POINT and TRIANGLE as a subclass of LINE.
The reason for including the (make-instance (gensym*)) in the LINE slots is to
provide the inheritance from the POINT class. With the standard Inheritance by
Specialization, only one position slot of LINE is possible because POINT has only
one position slot. It is not possible for both slot point1 and slot point2 of LINE to
inherit the position slot of POINT. The actual slot value of each LINE will be a
gensym* value. Each gensym* value will be the instance name of a point instance.
The point position can then be accessed through the gensym* value. Thus, the
gensym* values act as pointers to different instances.
The following examples show how the points are accessed for one-dimensional points
at position 0 and 1.
CLIPS> (definstances LINE_OBJECTS
(Line1 of LINE))
CLIPS> (reset)
CLIPS>
(0)
CLIPS>
(1)
[Line1] of LINE
(point1 [gen1])
(point2 [gen2])
CLIPS>
(0)
CLIPS>
CLIPS>
Now that you understand how the indirect access works, let's define some handlers to
avoid the trouble of entering the nested (send) messages, as in the last two cases. Let's
define a handler called find-point to print out a specified point value, and a handler
called print- points to print out the values of both LINE points as follows. The
argument of find-point will be either a 1 for point1 or a 2 for point2.
CLIPS> (defmessage-handler LINE find-point (?point)
(0)
(1)
CLIPS>
For real use, it would be best to provide error detection so that only a 1 or 2 is
allowed.
As you can see, the handler works fine for one-dimensional points. It can be tested for
two-dimensional points as follows. We'll assume the first number for each point is the
X- value, and the second number is the Y- value. That is, point1 has X- value 1 and
Y- value 2.
CLIPS> (send (send [Line1] get-point1) put-position 1 2)
(1 2)
(4 6)
(point1 [gen1])
(point2 [gen2])
(1 2)
(4 6)
CLIPS>
Now that we have the two point positions, it's easy to find the distance between the
points, which is the length of the line. The distance can be determined by defining a
new handler called find-distance which uses the Pythagorean Theorem to calculate the
distance as the square root of the sum of the squares. Since no assumptions were made
as to the number of dimensions, the (nth) function is used to pick out each multifield
value up the the maximum number of coordinates, as stored in the ?len variable.
CLIPS> (defmessage-handler LINE find-distance ()
(bind ?sum 0)
(bind ?index 1)
Distance = 5.0
CLIPS>
The values 1, 2 for point1 and 4, 6 for point2 were chosen for an easy check of the
handler since these coordinates define a 3-4-5 triangle. As you can see, the distance is
5.0, as expected.
Treasure Maps
Now that the POINT and LINE classes have been defined by generalized inheritance,
why stop now? Let's continue with the next simplest class that can be defined from a
line -- the triangle. Shown following are the three defclasses required.
(clear)
(propagation no-inherit)))
(propagation no-inherit))
(propagation no-inherit)))
(propagation no-inherit))
(slot line2 (create-accessor read-write)
(propagation no-inherit))
(propagation no-inherit)))
Notice that the (no-inherit) facets in TRIANGLE are techically not necessary since
there is no subclass of TRIANGLE defined. The reason for including the (no-inherit)
facets is because of defensive-programming, which is analogous to defensive- driving.
If another subclass is added, either by you or someone else, the (defclass) of
TRIANGLE must be modified to include the (no-inherit) facets. This is bad style
because it means that existing, debugged code must be modified. If you're going to
enhance existing, debugged code, you shouldn't have to modify it. It's better to plan
ahead for enhancements.
Next we'll define a triangle instance and check the instances generated. Note that your
gen values may be different from those shown unless you've just started or restarted
CLIPS, or have not used (gensym*) or (gensym) since you started.
CLIPS> (definstances TRIANGLE_OBJECTS
(Triangle1 of TRIANGLE))
CLIPS> (reset)
CLIPS> (instances)
[initial-object] of INITIAL-OBJECT
[Triangle1] of TRIANGLE
[gen3] of LINE
[gen4] of POINT
[gen5] of POINT
[gen6] of LINE
[gen7] of POINT
[gen8] of POINT
[gen9] of LINE
[gen10] of POINT
[gen11] of POINT
CLIPS>
At first you may be surprised at all the gensym* values created. However, all of them
are necessary. First, gen3 was created for slot line1, which required gen4 and gen5 for
the slots point1 and point2 associated with it by inheritance. Second, gen6 was created
for slot line2, which required gen7 and gen8 for its slots point1 and point2. Finally,
gen9 was created for slot line3, which required gen10 and gen11 for the slots point1
and point2 associated with it . The slots for [Triangle1] and one of its pointer values,
[gen3], is shown following.
CLIPS> (send [Triangle1] print)
[Triangle1] of TRIANGLE
(line1 [gen3])
(line2 [gen6])
(line3 [gen9])
[gen3] of LINE
(point1 [gen4])
(point2 [gen5])
CLIPS>
[Triangle1] of TRIANGLE
(line1 [gen3])
(line2 [gen6])
(line3 [gen9])
[gen3] of LINE
(point1 [gen4])
(point2 [gen5])
[gen4] of POINT
(position -1 0)
[gen5] of POINT
(position 0 2)
CLIPS>
As you can see, the line1 pointer [gen1] points to point1 and point2 with their pointers
[gen2] and [gen3]. These last two pointers finally point to the actual values of (-1 0)
and (0 2) that define line1 of [Triangle1]. It's analogous to Long John Silver finding a
treasure chest with a map, [gen1], which leads to another chest with two maps, [gen2]
and [gen3], which lead to the two buried treasures at the locations specified by [gen2]
and [gen3].
The values stored for each line of [Triangle1] can be retrieved by a single command
using nested messages such as the following.
(send (send (send [Triangle1] get-line1)
get-point1)
get-position)
Although these commands work, it's not much fun to type them in unless you get paid
by the hour and need the typing practice. As you might have guessed from the LINE
handlers that we defined in the previous section, it's possible to define TRIANGLE
handlers as follows.
(defmessage-handler TRIANGLE find-line-point (?line ?point)
point1 (-1 0)
point2 (0 2)
CLIPS>
Using these handlers is a lot more convenient than typing in the nested messages.
At this point, you might be tempted to define a handler called find-line which returns
both point values of the specified line. Recall that find-line-point requires the
specification of both the line and one of the two points which define the line. So why
not just send two messages in the same handler to return both point values of the
specified line? Shown following is the handler for find-line and what it returns for
line1 of [Triangle1].
(defmessage-handler TRIANGLE find-line (?line)
(0 2)
CLIPS>
As you can see, the handler only returns the last message value of (0 2). Thus, the first
value of (-1 0) is not returned by CLIPS. This is like the case of deffunctions which
only return the last action. One way of getting around this problem and returning both
point values of the line is shown following.
(defmessage-handler TRIANGLE find-line (?line)
(create$ (send (send (send ?self (sym-cat "get-line" ?line)) get-point1) get-
position)
(-1 0 0 2)
CLIPS>
Notice that the (create$) function was used to combine both point values into a single
multifield value (-1 0 0 2) which was then returned.
Other Features
A number of other functions are useful with handlers. Some of these follow.
Function Meaning
Function Meaning
get-defmessage-handler-list Groups the class names, message names and types (direct
or inherited)
class-superclasses Groups all superclass names (direct or inherited.)
slot-sources Groups the slot names of classes which contribute to a slot in the
specified class
The preview-send function is useful in debugging since it displays the sequence of all
handlers that potentially may be involved in processing a message. The reason for the
term potentially is that shadowed handlers will not be executed if the shadower does
not use call- next- handler or override- next- handler.
Function Meaning
In this chapter you'll learn how to pattern match on instances. One way is with rules.
Also, CLIPS has a number of query functions to match instances. In addition, control
facts and slot daemons can be used for pattern matching.
Object Lessons
One of the new features of Version 6.0 is the ability of rules to pattern match on
objects. In order to use this feature you must first specify whether a class is reactive to
pattern matching on the LHS of rules using the pattern-match role. If the pattern-
match is reactive, the class may be pattern matched. If the class is nonreactive, it is
not. The default is non-reactive.
You can also specify whether a slot facet reactive or non-reactive using the slot
facet pattern-match reactive or pattern-match non-reactive. The following
example shows how the value of the slot sound is pattern matched by a rule.
CLIPS> (clear)
CLIPS>
[Dorky_Duck]
[Dinky_Duck]
=>
(printout t "Duck " (instance-name ?duck) " says " ?find crlf))
CLIPS> (run)
CLIPS>
The object-pattern conditional element object is followed by the classes and slots to
be matched against. Following the is-a and the slot-name can be constraint
expressions involving ?, $?, &, and |.
In addition, instance names can be specified for pattern matching. The following
example shows how only one instance of the DUCK class is matched using the name
constraint, name, of instances. Note that name is a reserved word and cannot be used
as a slot name.
CLIPS> (defrule find-sound
=>
(printout t "Duck " (instance-name ?duck) " says " ?find crlf))
CLIPS> (run)
CLIPS>
Consider the following general type of problem. Given some instances, how many
satisfy a specified condition? For example, shown following are the defclasses and
definstances of Joe's Home showing the various types of sensors and the appliances
connected to them. Notice that an abstract class DEVICE is defined since both
SENSOR and APPLIANCE inherit common slots type and location.
(clear)
(definstances ENVIRONMENT_OBJECTS
(loc kitchen)
(min 20)
(max 100)
(app FR))
(loc bedroom)
(min 20)
(max 100)
(app FR))
(loc bedroom)
(min 1000)
(max 5000)
(app SA))
(loc basement)
(reading 0) ; OK
(min 0)
(max 0)
(app WP))
(loc basement)
(status on))
(loc basement)
(setting fixed)
(status off))
(loc basement)
(setting fixed)
(status off)))
Suppose the following questions or queries are asked. What are all the objects in the
database? How are all the objects arranged? What are the relationships between
objects? What are all the devices? What are all the sensors? What are all the
appliances? Which sensor is connected to which appliance? Are there any sensors
whose type is temperature? What sensors of type temperature have a reading between
min and the max? An even more basic query is whether or not there are any sensors
present.
The query system of COOL is a set of six functions that may be used for pattern
matching an instance-set and performing actions. An instance-set is a set of instances,
such as the instances of SENSOR. The instances in the instance-set may come from
multiple classes that do not have to be related. In other words, the classes do not have
to be from the same inheritance path.
The following table from the CLIPS Reference Manual, summarizes the predefined
query functions that may be used for instance-set access.
CLIPS> (instances)
[initial-object] of INITIAL-OBJECT
[T1] of SENSOR
[T2] of SENSOR
[S1] of SENSOR
[W1] of SENSOR
[FR] of APPLIANCE
[WP] of APPLIANCE
[SA] of APPLIANCE
CLIPS>
The basic format of a query function involves an instance-set-template to specifies the
instances and their classes, an instance-set-query as the boolean condition that the
instances must satisfy, and an action to specifies the single action to be taken.
Multiple actions can be included by grouping them with the progn function.The
predicate function class-existp returns TRUE if the class exists and FALSE otherwise.
The combination of instance name followed by the one or more class restrictions is
called an instancesetmembertemplate. The query functions may generally be used like
any other function in CLIPS. Shown following are the Rules of Scope which describe
the restrictions on the use of variables in a query function. The term scope means the
section of code where a variable is visible or known. The term reference means the
name or address by which a variable is accessed. In other words, the scope of a
variable means where the variable can be referenced, e.g., bound or printed. Anything
which is not prohibited by these rules is allowed, such as nesting. Also, the
term query refers to the query portion of the query function, not the query function
itself.
There are two steps involved in trying to satisfy a query. First, CLIPS generates all the
possible instance-sets that match the instance-set-template. Second, the boolean
instance-set-query is applied to all the instance-sets to see which ones, if any, satisfy
the query. Instance-sets are generated by a simple permutation of the members in a
template, where the rightmost members are varied first. Note that a permutation is not
the same as a combination because order matters in a permutation but not in a
combination.
The function find-all-instances returns a multifield value of all instances which satisfy
the query, or an empty multifield value for none. The do-for-instance query function
is similar to find-instance except that it performs a single distributed action when the
query is satisfied. The do-for-all-instances function is similar to the do-for-instance
except that it performs an action for every instance-set that satisfies the query.
Design Decisions
In contrast to rules which are only activated when their patterns are satisfied,
deffunctions are explicitly called and then executed. Just because a rule is activated
does not mean it will be executed. Deffunctions are completely procedural in nature
because once called by name, their code is executed in a procedural manner, statement
by statement. Also, no pattern matching involving constraints is used in a deffunction
to decide if its actions should be executed. Instead, any arguments that match the
number expected by the deffunction argument list will satisfy the deffunction and
cause its actions to be executed.
The basic idea of deffunctions as named procedural code is carried to a much greater
degree with defgenerics and the defmethods that describe their implementation. A
defgeneric is like a deffunction but much more powerful because it can do different
tasks depending on its argument constraints and types. The ability of a generic
function to perform different actions depending on the classes of its arguments is
called overloading the function name.
By proper use of operator overloading, it's possible to write code that is more readable
and reusable. For example, a defgeneric for the "+" function can be defined with
different defmethods. The expression,
(+ ?a ?b)
could add two real numbers represented by ?a and ?b, or two complex numbers, or
two matrices, or concatenate two strings, and so forth depending if there is a
defmethod defined for the argument classes. CLIPS does this by first recognizing the
type of the arguments and then calling the appropriate defmethod defined for those
types. A separate overloaded defmethod for "+" would be defined for each set of
argument types except for the predefined system types such as real numbers. Once the
defgeneric is defined, it's easy to reuse in other programs.
Any named function that is system defined or external can be overloaded using a
generic function. Notice that a deffunction cannot be overloaded. An appropriate use
of a generic function is to overload a named function. If overloading is not required,
you should define a deffunction or an external function.
The syntax of defgenerics is very simple, consisting of just the legal CLIPS symbol
name and an optional comment.
(defgeneric <name> [<comment>])
CLIPS>
It's not possible to do this comparison with the ">" function because it expects
NUMBER types as arguments.
However, it's easy to define a (defgeneric) which will overload the ">" to accept
STRING types as well as NUMBER types. For example, if the arguments of ">" are
of type STRING, the defgeneric will do a string comparison, letter by letter starting
from the left until the ASCII codes differ. In contrast, if the arguments of ">" are of
type NUMBER, the system compares the sign and magnitude of the numbers. The
user- defined ">" for STRING types is an explicit method, while a system-defined or
user-defined external function such as ">" for NUMBER type is an implicit method.
The technique of overloading a function name so that the method which implements it
is not known until run-time is another example of dynamic binding. Any object
reference of name or address may be bound at run-time in CLIPS to functions through
dynamic binding also.
Some languages such as Ada have a more restrictive type of overloading in which the
function name must be known at compile time rather than at run-time. The run-time
dynamic binding is the least restrictive since methods can be created during execution
by the (build) statement. However, you should be careful in using (build) since
dynamically creating constructs is often hard to debug. Also, the resulting code may
be difficult to verify and validate since you'll have to stop execution to examine the
code. Dynamic binding is a characteristics of a true object- oriented programming
language.
Following is an example of a defgeneric, ">", for STRING types and its method.
CLIPS> (defgeneric >) ; Header declaraction. Actually unnecessary
FALSE
FALSE
CLIPS>
The (defgeneric) acts as a header declaration to declare the type of function being
overloaded. It's not actually necessary to use a defgeneric in this case because CLIPS
implicitly deduces the function name from the defmethod name, which is the first
symbol following "defmethod". The header is a forward declaration that is necessary
if the (defgeneric) methods have not yet been defined, but other code such as defrules,
defmessage-handlers, and so forth refers to the (defgeneric) name.
Other Features
A shadowed method is one in which one method must be called by another. The
process by which CLIPS picks the method with highest precedence is called the
generic dispatch. For more information, see the CLIPS Reference Manual.
CLIPS is a productive development and delivery expert system tool which provides a
complete environment for the construction of rule and/or object based expert systems.
CLIPS is being used by over 4,000 users throughout the public and private community
including: all NASA sites and branches of the military, numerous federal bureaus,
government contractors, universities, and many companies. The key features of
CLIPS are:
G. Riley, C. Culbert, R. Savely, and F. Lopez, "CLIPS: An Expert System Tool for
Delivery and Training," Proceedings of the Third Conference on Artificial
Intelligence for Space Applications, Huntsville, AL, November 1987.
C. Culbert, G. Riley, R. Savely, and J. Giarratano, "A Solution to the Expert System
Delivery Problem," Proceedings of the ISA/88, Houston, TX, October 1988.
G. Riley, C. Culbert, and R. Savely, "CLIPS: An Expert System Tool for Training,
Development, and Delivery," Intelligent Systems Review, Volume 1, Number 1, Fall
1988.
Joseph C. Giarratano, Chris Culbert, and Robert T. Savely, "The State of the Art for
Current and Future Expert System Tools," ISA Transactions, Vol. 29, No. 1, pp. 17-
25, Jan. 1990
G. Riley and B. Donnell, "Advanced CLIPS Capabilities," Proceedings of The Fourth
Annual Workshop on Space Operations Applications and Research (SOAR `90),
NASA/Johnson Space Center, Albuquerque, NM, June 1990.
Joseph C. Giarratano and Gary Riley, Expert Systems Principles and Programming,
PWS Pub. Co.
A1.2-Ken Porter
B1.2-Grace Hua
B1.3-Stephen J. Mueller
Incorporating CLIPS into a Personal-Computer-Based Intelligent Tutoring System
A2.1-Barry W. Cameron
A2.2-Keith Morris
A3.1-Roger F. Hansen
A3.2-Albert Leigh
A3.3-Tom Wannemacher
Using CLIPS in A Distributed System - The Network Control Center (NCC) Expert
System
B3.1-Larry Mason
B3.3-Gary B. Young
A4.1-Ravi M. Rangan
B4.1-James L. Rogers
B4.2-Jaye Hicks
B4.3-Wesley A. White
A5.2-George D. Lardas
An Expert System to Manage the Operation of the Space Shuttle's Cryogenic Fuel
Tank Cryogenic Reactant Tanks
B5.2-James R. Geissman
A6.1-Donald Culp
A6.2-Arthur N. Rasmussen
B6.2-Robert H. Fritz
B6.4-Dr. Bernard A. Engel, D.D. Jones, R.L. Rhykerd, L.M. Rhykerd, C.L. Rhykerd,
Jr.
A CLIPS Expert System for Maximizing Alfalfa (Medicago Sativa L.) Production
A Decision Support System for Delivering Optimal Quality Peach and Tomato
A7.2-Richard O'Donnell
A7.3-Mark Tischendorf
A8.1-Christopher Marsh
B8.1-Dr. Bernard A. Engel, C.C. Rewerts, R. Srinivasan, J.B. Rogers, Dr. D.D. Jones
B8.2-Charles R. Patton
A9.1-Thomas P. Gathmann
A9.3-Barbara Pauls
CLIPS-A Tool for Corn Disease Diagnostic System and an Aid to Neural Network for
Automated Knowledge Acquisition
A11.1-Steve Geyer
CLIPS Meets the Connection Machine or How to Create a Parallel Production System
A11.2-David Goldstein
B11.1-Mark Auburn
B11.4-Clifford Sobkowicz
B12.1-Andres C. Callegari
B12.2-Ben M. Faul
Constructing Complex Graphics Applications with CLIPS and the X-Window System
A13.1-Matthew R. Barry
A13.2-Tim Conway
B13.1-Chet Lund
A14.1-Dr. Linfu Cheng, John D. McKendrick, Jeff Liu, Elcee Computek, Inc.
A14.2-Brett Gossage
B14.2-David J. Swanson
B14.3-Andrew Warinner
A15.1-Cody R. Nivins
Volume 1
Page
AGENDA 3
SESSION 1
SESSION 2A.
SESSION 2B
Shell for Building Expert Systems for Automated Prediction and Decision Making 89
SESSION 3A
SESSION 3B
Acquisition, Representation and Rule Generation for Procedural Knowledge 149
SESSION 4A
SESSION 4B
Generating Target System Specifications from a Domain Model Using CLIPS 209
Volume 2
SESSION 5A
SESSION 5B
SESSION 6A
SESSION 6B
SESSION 7A
Design Concepts for Integrating the IMKA Technology with CLIPS 395
On the Generation of Graphical Objects and Images from within CLIPS Using XView
417
SESSION 7B
SESSION 8A
PVEX - An Expert System for ProducibilityNalue
Engineering 455
SESSION 8B
To obtain updated and detailed information on all software tools developed by the
Software Technology Branch (STB), you may log onto the STB Bulletin Board. You
will find software release information, abstracts, information make-files, ordering
information, bug reports, work arounds, and much more. An option is also available to
communicate with NASA technical staff via email options. Anyone can use the BBS
whether they are a government user or not. Simply call up the BBS 24 hours a day,
and create yourself an individual account.
CLIPS: A productive development and delivery expert system tool which provides a
complete environment for the construction of rule and/or object based expert systems.
CLIPS is the first language to provide a verification/validation utility for the
development of expert systems. The key features of CLIPS are knowledge
representation, portability, integration/extensibility, interactive development, and
objects.
NETS: A software tool which provides an environment for the development and
evaluation of neural networks. With NETS you can create and execute arbitrary
configurations of neural networks which use the back propagation learning technique.
NETS is portable and will run on a variety of machines from mainframes to personal
computers.
Splicer: A genetic algorithm tool which can be used to solve search and optimization
problems. Genetic algorithms are adaptive search procedures based loosely on the
processes of natural selection and Darwinian "survival of the fittest." Splicer provides
the underlying framework and structure for building a genetic algorithm application.
Index
A
SYMBOL
| constraint, 60
U
V