RuleWorks

Rules' Right-Hand Sides: Actions

The right-hand side (RHS) is the "then" part of a rule. It consists of one or more actions. You can use the actions supplied by RuleWorks to perform the operations listed in the table below (each operation is listed with the constructs used to perform the operation).

Table 4-1: RuleWorks Actions

OperationAction
Bind variablesBIND action
Modify working memory MAKE action
COPY action
SPECIALIZE action
MODIFY action
REMOVE action
REMOVE_EVERY action
Work with compound valuesFOR_EACH action
Open and close filesOPENFILE action
CLOSEFILE action
Read input and write outputDEFAULT action
WRITE action
Use a catcherAFTER action
Save and restore the state of working memory and the conflict set SAVESTATE action
ADDSTATE action
RESTORESTATE action
Return control to the calling moduleRETURN action
Invoke the RuleWorks command interpreterDEBUG action
Control the flow of program executionIF … THEN … ELSE action
WHILE … DO … action
Stop program executionQUIT action

The first section of this chapter describes the format of RHS actions. The rest of this chapter explains how to perform the operations listed in the table above. You can also use external routines as actions on the RHS.

The Format of RHS Actions

An RHS action consists of a left parenthesis, an action name and its arguments, and a right parenthesis. The format for specifying an action is shown below:

( action-name [argument] ...)

For example:

Most RuleWorks actions require at least one argument. You can represent argument values with constants, bound variables, numeric expressions, or function calls. For example, the WRITE action above has one argument, a quoted symbolic atom.

Actions are allowed in rules, catchers, and in the ON- statements.

Most RHS actions have no return value. The MAKE, MODIFY, COPY, and SPECIALIZE actions do return values, and these actions can be used as functions on the RHS.

 

Binding Variables

Use the BIND action to bind a variable to a value. When you specify the BIND action with a variable and a right-hand-side expression, the run-time system evaluates the expression and binds the variable to the result. For example:

The run-time system evaluates the expression (<X> + 1) and binds the variable <Y> to the result.

The following action is from the example. It shows the result of a MAKE action being used in a BIND action:

 

Changing Working Memory

A RuleWorks program can modify the contents of working memory during execution. RuleWorks provides actions that create new objects, change existing objects, and delete objects.

Creating Working-Memory Objects

You can create new objects with either the MAKE or the COPY action. The MAKE action creates a new object of the class you specify. The COPY action creates a new object of the same class as the original object. You can also specify values for attributes with both the MAKE and COPY actions.

Using the MAKE Action

Use the MAKE action to create an object. You must specify a declared object class name as the first argument to the MAKE action. After the class name you can specify zero or more attribute-value pairs.

For example, the following MAKE action creates an object of class CONTEXT to initialize working memory:

This object is displayed as follows:

(The output above was produced by the WM command.)

If you do not specify attribute names and values in a MAKE action, the run-time system creates an object with default values for the unspecified attributes. If the attribute has no default value, the run-time system uses the atom NIL for scalar attributes and the empty list, (COMPOUND), for compound attributes.

Consider the following rule:

Example: 4-4 Rule

 

Neither MAKE action in this rule specifies any attribute values. However, classes BOX and KIWICALC both have inherited default values. Therefore, the objects created by this rule do have some attributes with non-NIL values in them. They would be displayed as shown below:

(See Figure 2-1 for an illustration of the class inheritance hierarchy of the sample configuration program, KIWI.RUL.)

The following example shows a MAKE action using the GET function to reference an attribute value indirectly:

Example: 4-2 MAKE Action using the GET Function

 

Using the COPY Action

Use the COPY action to duplicate, or duplicate and modify, an existing object. The first argument to the COPY action must be bound to a value of type INSTANCE-ID. The COPY action creates a new object of the same class as the one that was matched. After the $ID variable, you can specify zero or more attributes and their values.

If you do not specify attribute names and values in a COPY action, the run-time system uses the values in the object that is being copied, and you get an exact duplicate (except for the INSTANCE-ID and the time-tag). For example, if the following rule:

fires on the object made in Using the MAKE Action, the result is the following object:

Changing the Class of a Working-Memory Object

To convert an instance of a parent class to an instance of a descendent class, use the SPECIALIZE action. By default, this action does not change any attribute except for ^$INSTANCE-OF. You can specify attributes if you want.

The following rule shows one possible use of the SPECIALIZE action:

Example 4-3: Using the SPECIALIZE Action

Changing the Values in Working-Memory Objects

To change values in an object, use the MODIFY action with a value of type INSTANCE-ID. You can use any number of attribute-value pairs in a MODIFY action, even zero. The changed object retains its old values for all other attributes; only the attributes you specify have their values replaced.

You can have more than one MODIFY action on a RHS; the changes are applied in the specified order.

Suppose working memory contains the following BOX object:

and the following rule fires on it:

Example 4-4: Rule Expand-Part-Skeleton

After the rule fires, the BOX object is changed to:

Deleting Objects from Working Memory

The REMOVE action deletes objects from working memory. You use REMOVE with one or more values of type INSTANCE-ID that indicate the WMOs to be deleted.

For example, the following rule tallies up single item costs into a final total. This rule modifies the TOTAL-COST object and deletes each ITEM-COST object as soon as its cost is added to the total:

Example 4-5: Tallying Up Single Item Costs

The REMOVE-EVERY action deletes all the working-memory objects that are instances of a specified visible class or its subclasses. For example, the following ON-EXIT statement:

deletes all visible WMOs as the entry block exits.

 

Working with Compound Values

The same syntax for matching and binding compound attributes is used for modifying compound attributes.

The table below lists the RuleWorks functions that can be applied to compound values on the RHS.

Table 4-2: Functions for Compound Values

FunctionDescription
COMPOUNDReturns a new compound value from zero or more elements
LENGTHReturns the number of elements in a compound value
NTHReturns the value of the specified element
POSITIONReturns the index position of an element in a compound value
SUBCOMPOUNDReturns a compound value containing the specified subrange of a compound value (RHS only)

 

Modifying a Single Element

Changing the value of a single element of a compound attribute is called element-wise modification. You can change a single element and leave all other elements untouched. For example, the following MODIFY action replaces the first element of ^CARD-IN-SLOT but does not affect any other elements:

If the index expression used in an element-wise modification is greater than the current length of the compound value, elements other than the one specified may be changed. The specified element is set to the new value, as expected. In addition, all elements between the original end of the compound attribute and the new value receive the FILL value declared for that attribute (or NIL, if none was declared).

For example, if the ^CARD-IN-SLOT attribute has the following value:

Then the following action:

sets the seventh element of ^CARD-IN-SLOT to the value HD-30, and sets the previously-untouched elements five and six to NIL, because no FILL value is declared for ^CARD-IN-SLOT. The new compound value of ^CARD-IN-SLOT is thus:

Modifying the Entire Compound Value

If you want to modify a compound attribute so that it has fewer elements than before, you must replace the entire attribute value. Typically this is done using the SUBCOMPOUND or the COMPOUND function to create an entirely new compound value. Continuing with the ^CARD-IN-SLOT example above, the following action:

has the effect of deleting all but the first two elements.

Using Common Idioms for Compound Values

Compound values are frequently used to represent stacks and queues. This section shows the RuleWorks idioms for common operations on stacks and queues.

Adding an Element to the Beginning of a Compound Attribute (Push)

To push a new value onto a stack, create a new compound value from the new scalar value plus the current compound value. For example:

Removing an Element from the Beginning of a Compound Attribute (Pop)

To pop a value off a stack, replace the original compound attribute with a modified version that consists of elements 2 through the end. For example:

You could also use the SUBCOMPOUND function to pop a stack:

Adding an Element to the End of a Compound Attribute (Append)

To append a value to the end of a queue, create a new compound value from the current compound value plus the new scalar value. For example:

Splicing A Compound Attribute

The following example removes a particular value from a compound attribute and advances the remaining elements to close the gap.

Example 4-6: Splicing a Compound Attribute

 

Joining Compound Attributes

The following example joins two compound values:

Example 4-7: Joining Compound Attributes

 

Iterating Through a Compound Value

You can use the FOR-EACH action to write a loop that executes once for each element in a compound value. The FOR-EACH action can include any number of RHS actions. Using the FOR-EACH action is more efficient than executing a rule multiple times to achieve the same result.

For example, the following rule can be added to the program in the example, Using $ID Variables as Pointers, to reverse the list:

Example 4-8: Reversing the List

 

Performing Input and Output Operations

RuleWorks programs can read input from and write output to a terminal or a file. You can use RuleWorks actions to:

Opening Files

To open a file for reading or writing, use the OPENFILE action. Specify the action with a file identifier, a file specification, and one of the keywords IN, OUT, or APPEND. If you specify IN, the action opens an existing file for reading only. If you specify OUT, the action creates a new file and opens it for writing only. If you specify APPEND, the action opens an existing file for writing and sets the file pointer to the end of the file.

After opening a file, the action associates the file identifier with that file. For example, the following action opens the file CONFIG.DAT for reading and associates the file identifier INFIL with the file:

The example shows the ON-ENTRY statement of an entry block that opens a file. First, the OPENFILE action opens the file named in the argument for writing and associates the file identifier DATA-IN with the file. Next, the IF...THEN...ELSE... action checks whether the open succeeded by using the IS-OPEN function.

Example 4-9: Opening a File with Error-Checking

See Section C.1 for platform-specific restrictions on file names.

Once a file has been opened and associated with a file identifier, you can use that file for input or output operations by specifying the file identifier with the following actions, functions, and commands:

Setting the Default Input Source and Output Destination

Use the DEFAULT action to set the default source for input operations or the destination for output operations. The argument values that you specify with the action determine the source or destination.

By default, input comes from the terminal. To set the source to a file, specify the DEFAULT action with the file identifier of an open input file and the keyword ACCEPT. Suppose INFIL is the file identifier for an open input file. The following action sets that file to be the default source for input:

Once the default for input has been set to a file, all input required by the ACCEPT-ATOM and ACCEPTLINE-COMPOUND functions is taken from that file. To set the default back to the terminal, specify the symbol NIL with the keyword ACCEPT.

The terminal is also the default destination for output. To set the destination to a file, specify the DEFAULT action with the file identifier of an open output file and the keyword TRACE or WRITE. The keyword TRACE sets the destination for output from the TRACE command, and the keyword WRITE sets the destination for the WRITE action. Suppose OUTFIL is the file identifier for an open output file. The following action sets that output file to be the default destination for trace output:

Once the destination for trace output has been set to a file, all trace output produced by the run-time system is sent to that file. Likewise, if you substitute the keyword WRITE for TRACE, all output produced by the WRITE action is sent to that file.

To set the default destination back to the terminal, specify the symbol NIL with the appropriate keyword. For example:

Reading Input

The input functions ACCEPT-ATOM and ACCEPTLINE-COMPOUND read values from the terminal or a file. By default, the input functions read input from the terminal. If you want to read from a file, call the input function with the file identifier of an open input file or change the default for input.

The input functions create atoms of the appropriate data types in exactly the same way as the compiler

The examples in the following sections assume that the file identified by INFIL contains the lines shown in the example.

Example 4-10: A Sample Input File

Both input functions ignore any atoms between a semicolon (;) and the end of the line.

Reading Scalar Atoms

The ACCEPT-ATOM function reads a single atom from the terminal or a file. For example, the following rule uses the ACCEPT-ATOM function inside a MAKE action to take items from a file into a WMO:

Example 4-11: Reading Scalar Atoms

Each time this rule fires, the attribute ^ITEM in a new WMO is given the value read by the ACCEPT-ATOM function. Given the data shown in the example, the following objects are created:

When the ACCEPT-ATOM function reads past the end of a file, it returns the atom END-OF-FILE.

The ACCEPT-ATOM function ignores blank lines between atoms.

Reading Compound Values

The ACCEPTLINE-COMPOUND function reads a line of input consisting of zero or more atoms and returns a compound value. Unlike the ACCEPT-ATOM function, the ACCEPTLINE-COMPOUND function does not ignore blank lines. You can specify a default value that the function returns when it reads a blank line. This default value can be a compound value or a bound compound variable.

For example, the MAKE action in the following rule calls the ACCEPTLINE-COMPOUND function with the default value (COMPOUND NOTHING HERE):

Example 4-12: Reading Compound Values

Given the data shown in the example, this rule makes the following objects:

If you want to specify a default value for ACCEPTLINE-COMPOUND, you must put a file identifier before the default value. If you want a default value even when reading from the default input source, use NIL for the file identifier.

When the ACCEPTLINE-COMPOUND function reads past the end of a file, it returns a compound value containing the single element END-OF-FILE.

Writing Output

Use the WRITE action to send output to the terminal or a file. If you want to send output to a file, specify the action with the file identifier of an open output file or change the default for the WRITE action.

The arguments that you specify for a WRITE action are evaluated, and the output is written on the current output line with one space between values. For example, suppose the variable <ITEM> is bound to COLOR-MONITOR and the variable <PRICE> is bound to 199.95. You could use these variables in a WRITE action as follows:

This action displays the following output:

The output is in capital letters because the RuleWorks compiler uppercases all unquoted symbols. To display output exactly the way you have entered it, enclose the text in vertical bars (| | ). For example:

This action displays:

If the variable <ITEM> were also inside vertical bars, it would not be evaluated. To get the value of <ITEM> in lowercase letters, it would have to be quoted in the place it was bound, not in the WRITE action.

Compound values are printed with one space between elements, but without any parentheses or the COMPOUND keyword. The following WRITE action:

could produce this output:

You can control the format of your output by using the CRLF, TABTO, and RJUST functions to:

Producing Output on a New Line

To write output on a new line, use the CRLF function in a WRITE action. For example:

Example 4-13: Producing Output on a New Line

The WRITE actions in this rule produce the following output:

Specifying the Column in Which to Start Writing Output

Use the TABTO function to specify in which column the WRITE action is to start writing output. Specify the column number with an integer or a variable bound to an integer. For example:

If the column you specify is to the left of the last column in which output has been written, the WRITE action writes the output on a new line, starting at the specified column.

The following WRITE action displays the headers of three columns:

This action produces the following output:

Producing Right-Justified Output

The WRITE action writes output right justified in a field of a specified width if you use the RJUST function. Specify the width with an integer or a variable bound to an integer. When a WRITE action contains the RJUST function, the WRITE action:

If the output being written requires more character positions than you specify for the field, the WRITE action writes the output as if the RJUST function was not specified, that is, the WRITE action inserts one space and then writes the output.

A call to the RJUST function must directly precede the value being written. You can use the RJUST function after calls to the CRLF and TABTO functions. For example:

You can also use the RJUST function to suppress the spaces that RuleWorks automatically inserts between values. For example:

Closing Files

To close files, specify the CLOSEFILE action with the file identifiers of the files you want to close. The action closes the files associated with the file identifiers you specify and dissociates the identifiers from the files. For example, to close files whose file identifiers are INFIL and OUTFIL, specify the following:

Once you have closed a file, you can no longer use its file identifier with other actions, functions, or commands to perform input and output operations. To use the files again, you must reopen them.

If you do not close your files when control leaves the current entry block, the files remain open when control returns to that entry block. If files are open when a program quits or exits, they are closed by the operating system.

 

Saving and Restoring Working Memory

You can copy the program state, that is, the state of working memory and the conflict set, to a file by using the SAVESTATE action. The SAVESTATE action is scoped to the entry block; thus, it saves only that portion of working memory that is currently visible. The following action copies the program state to the file CONFIG.DAT:

(See Section C.1 for platform-specific restrictions on file names.)

Once you have saved the program state in a file, you can use the ADDSTATE action to add the contents of the saved working memory stored in that file to the current program state. Like the SAVESTATE action, the ADDSTATE action is scoped to the entry block; it can create only those objects that are visible.

If you want to clear the program state and restore it to the state produced by the SAVESTATE action, use the RESTORESTATE action. Like SAVESTATE and ADDSTATE, the RESTORESTATE action is scoped to the entry block; it can create only those objects that are visible. Using ADDSTATE or RESTORESTATE to create objects whose declarations are currently unknown results in a run-time warning.

Suppose you have used the SAVESTATE action to copy the program state to the file CONFIG.DAT. You can use the following action to clear and restore the program state to that recorded in the file CONFIG.DAT:

The state of user-defined external routines, and of files, is not saved by the SAVESTATE action and thus cannot be added or restored with the ADDSTATE or RESTORESTATE action.

If you change your OBJECT-CLASS declarations before using ADDSTATE or RESTORESTATE, the old saved file is useless.

 

Controlling the Flow of Program Execution

RuleWorks provides two RHS actions that allow you to control the flow of execution, as in procedural languages: IF...THEN...ELSE and WHILE...DO... These control actions are especially useful in ON-ENTRY statements, to allow an entry block to respond correctly to its input arguments.

Both control actions evaluate a relational expression to determine which, if any, actions are executed. The next section explains relational expressions; the following two sections cover the IF...THEN...ELSE... and WHILE...DO... actions in detail.

Relational Expressions

Relational expressions on the RHS are similar to attribute-value tests on the LHS, except that relational expressions compare two values instead of an attribute and a value, and evaluate to TRUE or FALSE instead of producing a match or no match. The syntax for a simple relational expression is shown below:

The values may be any expression; the relational operators may be any one of the match predicates (see Table 3-2). The restrictions on domain and shape (data type and scalar or compound) shown in the table also apply when you use the predicates in relational expressions. For example, assuming <THE-ID> is a $ID variable, the following code generates a compile-time warning:

because the less-than operator is valid only for numbers and symbols. Assuming the variable <COUNT> is bound to either an INTEGER or a FLOAT value, the following code is correct:

If, at run-time, <COUNT> is bound to a value of any non-numeric type, the expression above generates no warnings, but it always evaluates to FALSE.

Note that while relational expressions evaluate to either TRUE or FALSE, TRUE and FALSE themselves are not valid relational expressions in RuleWorks.

You can use the relational operators AND, NOT, and OR to combine two (or invert one, in the case of NOT) simple relational expressions into a more complex relational expression. For example:

Selecting Actions (Branching)

The IF...THEN...ELSE... action allows you to select between two sets of actions based on the result of a relational expression (see previous section). The syntax of this action is shown in the following example.

Example 4-14: IF-THEN-ELSE Syntax

The RHS actions in the THEN clause are executed when the relational expression evaluates to TRUE; the actions in the ELSE clause (if any) are executed when the relational expression evaluates to FALSE. The example show IF...THEN...ELSE... actions in ON-ENTRY statements.

Repeating Actions (Looping)

The WHILE...DO... action allows you to repeat (iterate) a set of actions based on the result of a relational expression (see Relational Expressions). The syntax of this action is shown below:

Example 4-15: WHILE-DO Syntax

The RHS actions are repeated as long as the relational expression evaluates to TRUE. Remember to include an action that affects the relational expression somewhere in your loop. In the following example, Reading a File, in a Loop the BIND action at the end of the loop resets the variable <IN-LINE> which is part of the relational expression.

 

Stopping Program Execution

Use the QUIT action to terminate execution of the current image and return control to the operating system without executing any ON-EXIT actions. Valid arguments for QUIT include $FAILURE and $SUCCESS, as well as any integer. RuleWorks substitutes either 0 or 1, as appropriate for the operating system, for $FAILURE and $SUCCESS.

The following example uses the QUIT action to terminate execution with a return value indicating success.

 

Example 4-16: Reading a File in a Loop

When this rule fires, the QUIT action causes the run-time system to stop executing recognize-act cycles immediately. The compiler provides a warning when any actions follow RETURN or QUIT actions.