Download Jess in Action e-book

Transcript
130
CHAPTER 7
Writing rules in Jess
results to return. That explains the (while (?it hasNext) ...(call ?it next))
control structure; it steps through each of the results returned by the query.
Each individual result is a jess.Token object. A Token is just a collection of
jess.Fact objects; each Token holds one match for the query. You call the fact()
method of jess.Token to retrieve the individual jess.Fact objects within the
Token. Each match begins with an extra fact, a query trigger fact that initiates the
matching process; it is asserted by the run-query command (this fact is retracted
automatically after the query is run). Hence the argument to the call to fact() is
1, not 0. Once you have the right fact, you use the fact-slot-value function to
extract the contents of the name slot. Printing the name slot of each fact leads to
the output shown earlier.
The defquery construct can use virtually all the same features that defrule
LHSs can, including all the special conditional elements described in this chapter.
The function ppdefrule can also pretty-print queries. Jess treats a defquery as a
special kind of defrule in many contexts; for instance, the rules command lists
defquerys as well as defrules.
As you can see, the run-query function lets you pass parameters to a query; you
passed numbers representing the upper and lower limits of a price range to the
find-affordable-gifts query. Let’s examine this process a little more closely.
7.7.1 The variable declaration
You might have already realized that two different kinds of variables can appear in
a query: those that are internal to the query, like ?p in find-affordable-gifts,
and those that are external, or to be specified in the run-query command when
the query is executed. Jess assumes all variables in a query are internal by default;
you must declare any external variables explicitly using this syntax:
(declare (variables ?x ?y ...))
When you invoke a query using the run-query function, you must supply exactly as
many variables as are listed in the variables declaration. Some queries may not
have any external variables; in this case, the variables declaration is optional.
7.7.2 Query trigger facts
When Jess compiles a defquery, it inserts an extra pattern as the first one in the
query. This first pattern is of the form
(__query-trigger-name ?x ?y ...)
where name is the name of the query and ?x, ?y, and so on are the variables
named in the variables declaration for the query. run-query works by asserting