You are on page 1of 77

Chapter 8:

Advanced Pattern
Matching

Expert Systems: Principles and


Programming, Fourth Edition
Objectives
• Learn about field constraints
• Learn how to use functions and expressions
• Learn how to perform summing values using
rules
• Learn how to use the bind function

• Learn how to use I/O functions

Expert Systems: Principles and Programming, Fourth Edition 2


Objectives
• Examine the two-player game called Sticks
• Learn how to use the test conditional element
• Learn how to use the predicate field constraint
and the return value constraint
• Examine the or, and, not, exists, forall logical
elements.

Expert Systems: Principles and Programming, Fourth Edition 3


Field Constraints
• In addition to pattern matching capabilities and
variable bindings, CLIPS has more powerful
pattern matching operators.
• Consider writing a rule for all people who do not
have brown hair:
– We could write a rule for every type of hair color that
is not brown.
– This involves testing the condition in a roundabout
manner – tedious, but effective.

Expert Systems: Principles and Programming, Fourth Edition 4


Field Constraints
• The technique for writing a rule for all non-
brown hair colors implies that we have the ability
to supply all hair colors – virtually impossible.
(defrule black-hair-is-not-brown
(person (name ?name)(hair black))
=>
(printout t ?name “ does not have brown color” crlf))
• An alternative is to use a field constraint to
restrict the values a field may have on the LHS –
the THEN part of the rule.
Expert Systems: Principles and Programming, Fourth Edition 5
Connective Constraints
• Connective constraints are used to connect
variables and other constraints.
• Not connective – the ~ acts on the one constraint or
variable that immediately follows it.
• Or constraint – the symbol | is used to allow one or
more possible values to match a field or a pattern.
• And constraint – the symbol & is useful with
binding instances of variables and on conjunction
with the not constraint.

Expert Systems: Principles and Programming, Fourth Edition 6


Field Constraints
Example (NOT constraint):

(defrule black-hair-is-not-brown
(person (name ?name)(hair ~brown))
=>
(printout t ?name “ does not have brown color” crlf))

Expert Systems: Principles and Programming, Fourth Edition 7


Field Constraints
Example (OR constraint):

(defrule black-or-brown-hair
(person (name ?name)(hair black | brown))
=>
(printout t ?name “ does not have brown color” crlf))

Expert Systems: Principles and Programming, Fourth Edition 8


Combining Field Constraints
• Field constraints can be used together with
variables and other literals to provide powerful
pattern matching capabilities.
• Example #1: ?eyes1&blue|green
– This constraint binds the person’s eye color to the
variable, ?eyes1 if the eye color of the fact being
matched is either blue or green.
• Example #2: ?hair1&~black
– This constraint binds the variable ?hair1 if the hair
color of the fact being matched is not black.

Expert Systems: Principles and Programming, Fourth Edition 9


Field Constraints
Example (AND constraint):

(defrule neither-black-nor-brown-hair
(person (name ?name)(hair ?color&~black&~brown))
=>
(printout t ?name “ has “ ?color “ hair color” crlf))

Question: what about using & and | together? What is the


precedence order between them?

Expert Systems: Principles and Programming, Fourth Edition 10


Functions and Expressions
• CLIPS has the capability to perform calculations.
• The math functions in CLIPS are primarily used for
modifying numbers that are used to make inferences by
the application program.

Expert Systems: Principles and Programming, Fourth Edition 11


Numeric Expressions in CLIPS

• Numeric expressions are written in CLIPS in


LISP-style – using prefix form – the operator
symbol goes before the operands to which it
pertains.
• Example #1:
5 + 8 (infix form)  + 5 8 (prefix form)

• Example #2:
(infix) (y2 – y1) / (x2 – x1) > 0
(prefix) (> ( / ( - y2 y1 ) (- x2 x1 ) ) 0)

Expert Systems: Principles and Programming, Fourth Edition 12


Functions and Expressions
• (* <numeric-expression> <numeric-expression>+)
CLIPS>(* 2 4 3)
24
• (+ <numeric-expression> <numeric-expression>+)
CLIPS>(+ 2 4 3)
9
• (- <numeric-expression> <numeric-expression>+)
CLIPS>(- 2 4 3)
-5
• (/ <numeric-expression> <numeric-expression>+)
CLIPS>(/ 2 4 3)
0.16666667

Expert Systems: Principles and Programming, Fourth Edition 13


Functions and Expressions
• (= <numeric-expression> <numeric-expression>+)
returns TRUE only if all are equal.
• (> <numeric-expression> <numeric-expression>+)
returns TRUE only if each argument n-1 is greater than argument n.

• (>= <numeric-expression> <numeric-expression>+)

• (< <numeric-expression> <numeric-expression>+)

• (<= <numeric-expression> <numeric-expression>+)


• (<> <numeric-expression> <numeric-expression>+)
returns TRUE only if the first argument is not equal to each of other
arguments.

Expert Systems: Principles and Programming, Fourth Edition 14


Functions and Expressions
• (max <numeric-expression> <numeric-expression>+)

• (min <numeric-expression> <numeric-expression>+)

• (abs <numeric-expression>)

• (float <numeric-expression>)

• (integer <numeric-expression>)

Expert Systems: Principles and Programming, Fourth Edition 15


Return Values
• Most functions (addition) have a return value that
can be an integer, float, symbol, string, or
multivalued value.
• Some functions (facts, agenda commands) have
no return values – just side effects.
• Division results are usually rounded off (always
converted to a float).
• Return values for +, -, and * will be integer if all
arguments are integer, but if at least one value is
floating point, the value returned will be float.

Expert Systems: Principles and Programming, Fourth Edition 16


Variable Numbers of Arguments

• Many CLIPS functions accept variable numbers of


arguments.
• Example:
CLIPS> (- 3 5 7)  returns 3 - 5 =-2 - 7 = -9
• There is no built-in arithmetic precedence in CLIPS
– everything is evaluated from left to right.
• To compensate for this, precedence must be
explicitly written.

Expert Systems: Principles and Programming, Fourth Edition 17


Variable Numbers of Arguments
Example: 2+3*4
CLIPS>(+ 2 (* 3 4))
14

(2+3)*4
CLIPS>(* (+ 2 3) 4)
20

Expert Systems: Principles and Programming, Fourth Edition 18


Embedding Expressions
• Expressions may be freely embedded within other
expressions:

Expert Systems: Principles and Programming, Fourth Edition 19


Embedding Expressions

Example:
CLIPS>(deftemplate person (slot name) (slot salary))
CLIPS>(assert (person (name “ali”) (salary (+ 300 400))))

Expert Systems: Principles and Programming, Fourth Edition 20


Summing Values Using Rules
• Suppose you wanted to sum the areas of a group
of rectangles.
– The heights and widths of the rectangles can be
specified using the deftemplate:
(deftemplate rectangle (slot height) (slot
width))
• The sum of the rectangle areas could be specified
using an ordered fact such as:
(sum 20)

Expert Systems: Principles and Programming, Fourth Edition 21


Summing Values
• A deffacts containing sample information is:
(deffacts initial-information
(rectangle (height 10) (width 6))
(rectangle (height 7) (width 5)
(rectangle (height 6) (width 8))
(rectangle (height 2) (width 5))
(sum 0))

Expert Systems: Principles and Programming, Fourth Edition 22


Summing Values
• (defrule sum-rectangle
(rectangle (height ?height)(width ?width))
?sum <- (sum ?total)
=>
(retract ?sum)
(assert (sum (+ ?total (* ?height ?width)))))

This rule will produce an infinite loop.

Expert Systems: Principles and Programming, Fourth Edition 23


Summing Values

Expert Systems: Principles and Programming, Fourth Edition 24


Summing Values
• Test the following with the previous example:

CLIPS>(watch rules)
CLIPS>(watch activations)
CLIPS>(watch facts)
CLIPS>(reset)
CLIPS>(run)

Expert Systems: Principles and Programming, Fourth Edition 25


The Bind Function
• Sometimes it is advantageous to store a value in a
temporary variable to avoid recalculation.
• The bind function can be used to bind the value
of a variable to the value of an expression using
the following syntax:

(bind <variable> <value>)

Expert Systems: Principles and Programming, Fourth Edition 26


The Bind Function
• (defrule sum-areas
?sum <- (sum ?total)
?new-area <- (add-to-sum ?area)
=>
(retract ?sum ?new-area)
(printout t “ New sum is “ (+ ?total ?area)  crlf)
(assert (sum (+ ?total ?area ))))

Expert Systems: Principles and Programming, Fourth Edition 27


The Bind Function
• (defrule sum-areas
?sum <- (sum ?total)
?new-area <- (add-to-sum ?area)
=>
(retract ?sum ?new-area)
(bind ?New-total (+ ?total ?area))
(printout t “ New sum is “  ?New-total crlf)
(assert (sum ?New-total)))

Expert Systems: Principles and Programming, Fourth Edition 28


I/O Functions
• When a CLIPS program requires input from the user of a
program, a read function can be used to provide input
from the keyboard:
CLIPS>(defrule get-name
=>
(printout t “What is your name? “)
(bind ?response (read))
(assert (user’s-name ?response))) 
CLIPS>(reset) 
CLIPS>(run)
What is your name? Ali 

Expert Systems: Principles and Programming, Fourth Edition 29


Read Function from Keyboard
• The read function can only input a single field at
a time.
• Characters entered after the first field up to the
 are discarded.
• To input, say a first and last name, they must be
delimited with quotes, “xxx xxx”.
• Data must be followed by a carriage return to be
read.

Expert Systems: Principles and Programming, Fourth Edition 30


I/O Functions
CLIPS>(facts) 
f-0 (initial-facts)
f-1 (user’s name Ali)

• The read could be used to input only one single


field.

What is your name? Ali Salim


; two fields, only the first is taken.
What is your name? “Ali Salim”
; one field

Expert Systems: Principles and Programming, Fourth Edition 31


I/O from/to Files
• Input can also come from external files.
• Output can be directed to external files.
• Before a file can be accessed, it must be opened
using the open function:
Example:
(open “mydata.dat” data “r”)
• mydata.dat – is the name of the file (path can also
be provided)

Expert Systems: Principles and Programming, Fourth Edition 32


I/O from/to Files
• data – is the logical name that CLIPS associates
with the file
• “r” – represents the mode – how the file will be
used – here read access
• The open function acts as a predicate function
– Returns true if the file was successfully opened
– Returns false otherwise

Expert Systems: Principles and Programming, Fourth Edition 33


File Access Modes

CLIPS>(open “C:\myfile.dat” data “r”) 


CLIPS>(open “C:\myfile.dat” data “r+”) 

Return false if the file does not exist.

Expert Systems: Principles and Programming, Fourth Edition 34


Close Function
• Once access to the file is no longer needed, it
should be closed.
• Failure to close a file may result in loss of
information.
• General format of the close function:
(close [<file-ID>])
(close data)  example

Expert Systems: Principles and Programming, Fourth Edition 35


Reading / Writing to a File
• Which logical name used, depends on where information
will be written – logical name t refers to the terminal
(standard output device).

Expert Systems: Principles and Programming, Fourth Edition 36


Reading / Writing to a File
CLIPS> (open "C:\mydata.dat" data "r")
TRUE my name faisal alkhateeb
CLIPS> (read data)
my
CLIPS> (read data)
name
CLIPS> (defrule read-file
=>(bind ?var (read data)) (printout t "?var= "  ?var crlf))
CLIPS> (run)
?var=faisal
CLIPS>

Expert Systems: Principles and Programming, Fourth Edition 37


Formatting
• Output sent to a terminal or file may need to be
formatted – enhanced in appearance.
• To do this, we use the format function which
provides a variety of formatting styles.
• General format:
(format <logical-name> <control-
string> <parameters>*)

Expert Systems: Principles and Programming, Fourth Edition 38


Formatting
• Logical name – t – standard output device; or
logical name associated with a file.
• Control string:
– Must be delimited with quotes
– Consists of format flags to indicate how parameters
should be printed
– 1 – 1 correspondence between flags and number of
parameters – constant values or expressions
– Return value of the format function is the formatted
string – nil can be used to suppress printing.

Expert Systems: Principles and Programming, Fourth Edition 39


Formatting
• Example:
(format nil “Name: %-15s Age: %3d” “Bob Green”
35) 
Produces the results:
“Name: Bob green Age: 35”

The format flag “%-15s” is used to print name in a


column that is 15 characters wide in a left
justified manner.

Expert Systems: Principles and Programming, Fourth Edition 40


Specifications of Format Flag

%-M.Nx

• The “-” means to left justify (right is the default)


• M – total field width – no truncation occurs (if
the output exceeds M columns, the format
function will expand the field as needed).
• N – number of digits of precision – default = 6
• x – display format specification

Expert Systems: Principles and Programming, Fourth Edition 41


Table 8.3 Display Format
Specifications

Expert Systems: Principles and Programming, Fourth Edition 42


Expert Systems: Principles and Programming, Fourth Edition 43
Readline Function
• To read an entire line of input, the readline function can be used:
(readline [<logical-name>])
• Example:
CLIPS>(defrule get-name
=>
(printout t “What is your name? “
(bind ?response (readline))
(assert (user’s-name ?response)))
CLIPS>(reset)
CLIPS>(run)
What is your name? Faisal Alkhateeb 
CLIPS>(facts)
f-0 (initial-fact)
f-1 (user’s-name “Faisal Alkhateeb”)
For a total of 2 facts.

Expert Systems: Principles and Programming, Fourth Edition 44


Readline Function
• The result of the readline function is stored as a single field, and thus it is
impossible to retrieve its parts (e.g. first and last name). To do so, the function
explode$ is used, which accepts a single string argument and converts it
to a multifield value.
• CLIPS>(defrule get-name
=>
(printout t “What is your name? “
(bind ?response (explode$ (readline)))
(assert (user’s-name ?response)))
CLIPS>(reset)
CLIPS>(run)
What is your name? Faisal Alkhateeb 
CLIPS>(facts)
f-0 (initial-fact)
f-1 (user’s-name Faisal Alkhateeb)
For a total of 2 facts.
Expert Systems: Principles and Programming, Fourth Edition 45
Expert Systems: Principles and Programming, Fourth Edition 46
Predicate Functions
• A predicate function is defined to be any function that returns:
– TRUE
– FALSE
• Any value other than FALSE is considered TRUE.
• We say the predicate function returns a Boolean value. They may
be either user-defined or pre-defined.
CLIPS>(and (> 4 3) (> 4 5)) 
FALSE
CLIPS>(or (> 4 3) (> 4 5)) 
TRUE
CLIPS>(not (> 4 3)) 
FALSE

Expert Systems: Principles and Programming, Fourth Edition 47


Some Predicate Functions
• (floatp <expression>)
Returns TRUE if <expression> is a float, FALSE otherwise.
• (integerp <expression>)
Returns TRUE if <expression> is an integer, FALSE otherwise.
• (evenp <expression>)
Returns TRUE if <expression> is an even integer, FALSE otherwise.
• (oddp <expression>)
Returns TRUE if <expression> is an odd integer, FALSE otherwise.
• (lexemep <expression>)
Returns TRUE if <expression> is a string or symbol, FALSE otherwise.
• (numberp <expression>)
Returns TRUE if <expression> is a float or integer, FALSE otherwise.

Expert Systems: Principles and Programming, Fourth Edition 48


The Test Conditional Element
• Processing of information often requires a loop.
• Sometimes a loop needs to terminate
automatically as the result of an arbitrary
expression.
• The test condition provides a powerful way to
evaluate expressions on the LHS of a rule.
• Rather than pattern matching against a fact in a
fact list, the test CE evaluates an expression –
outermost function must be a predicate function.

Expert Systems: Principles and Programming, Fourth Edition 49


Test Condition
• A rule will be triggered only if all its test CEs are
satisfied along with other patterns.

(test <predicate-function>)

Example:
(test (> ?value 1))

Question: what about if a test condition is the only


pattern in the rule?
Expert Systems: Principles and Programming, Fourth Edition 50
Test Condition
CLIPS> (defrule enter-number
=>
(bind ?number (read))(assert (input ?number)))
==> Activation 0 enter-number: f-0
CLIPS> (defrule check-positive-number
(input ?value)
(test (and (integerp ?value) (>= ?value 0)))
=>
(printout t ?value " is a positive integer"
crlf))

Expert Systems: Principles and Programming, Fourth Edition 51


Expert Systems: Principles and Programming, Fourth Edition 52
Test Condition
CLIPS> (rules)
enter-number
check-positive-number
For a total of 2 defrules.
CLIPS> (run)
70
==> Activation 0 check-positive-number:
f-1
70 is a positive integer
CLIPS>

Expert Systems: Principles and Programming, Fourth Edition 53


Predicate Field Constraint
• The predicate field constraint : allows for
performing predicate tests directly within
patterns. The operators & | ~ operators could be
used with this type of constraints.
• The predicate field constraint is more efficient
than using the test CE.
• It can be used just like a literal field constraint –
by itself or part of a complex field.
• The predicate field constraint is always followed
by a function for evaluation (predicate function).

Expert Systems: Principles and Programming, Fourth Edition 54


Predicate Field Constraint

Example: instead of the following two


patterns
(data ?size)
(test (> ?size 1))

Could be rewritten as one pattern:


(data ?size&: (> ?size 1))

Expert Systems: Principles and Programming, Fourth Edition 55


Predicate Field Constraint
CLIPS> (defrule float-or-integer
(data ?item&: (integerp ?item)|:(floatp
?item))
=>(printout t ?item " is a float or
integer" crlf))
CLIPS> (reset)
CLIPS> (assert (data 20))
==> Activation 0 float-or-integer : f-1
CLIPS> (run)
20 is a float or integer

Expert Systems: Principles and Programming, Fourth Edition 56


Predicate Field Constraint
CLIPS> (defrule data-type
(data ?item&~: (integerp ?item))
=>(printout t ?item " is not an
integer" crlf))
CLIPS> (reset)
CLIPS> (assert (data 20.5))
==> Activation 0 data-type : f-1
CLIPS> (run)
20.5 is not an integer

Expert Systems: Principles and Programming, Fourth Edition 57


Predicate Field Constraint
CLIPS> (defrule integer-ge10
(data ?item&: (integerp ?item)&:(?item
>10))
=>(printout t ?item " is an integer
greater than 10" crlf))
CLIPS> (reset)
CLIPS> (assert (data 20))
==> Activation 0 integer-ge10 : f-1
CLIPS> (run)
20 is an integer greater than 10

Expert Systems: Principles and Programming, Fourth Edition 58


Return Value Constraint
• The return value constraint = allows the return
value of a function to be used for comparison
inside a pattern.
• The return value constraint must be followed by a
function (not necessarily a predicate function).
• The function must have a single-field return
value.

Expert Systems: Principles and Programming, Fourth Edition 59


Return Value Constraint
CLIPS> (defrule return-value
(person (name ?name )(age =(mod 30 4)))
=> (printout t ?name crlf))
CLIPS> (rules)
return-vale
For a total of 1 defrule.
CLIPS> (agenda)
CLIPS> (assert (person (name ali)(age 13)))
<Fact-1>
CLIPS> (agenda)
CLIPS> (assert (person (name ahmad)(age 2)))
==> Activation 0 return-vale: f-2
<Fact-2>
CLIPS>
Expert Systems: Principles and Programming, Fourth Edition 60
The OR Conditional Element
• Consider the two rules:

Expert Systems: Principles and Programming, Fourth Edition 61


OR Conditional Element
These two rules can be combined into one rule – or CE
requires only one CE be satisfied:

Expert Systems: Principles and Programming, Fourth Edition 62


The And Conditional Element
The and CE is opposite in concept to the or CE –
requiring all the CEs be satisfied:

Expert Systems: Principles and Programming, Fourth Edition 63


Not Conditional Element
When it is advantageous to activate a rule based on the
absence of a particular fact in the list, CLIPS allows the
specification of the absence of the fact in the LHS of a
rule using the not conditional element:

Expert Systems: Principles and Programming, Fourth Edition 64


Not Conditional
We can implement this as follows:

Expert Systems: Principles and Programming, Fourth Edition 65


Not Conditional
CLIPS> (deftemplate emergency (slot type))
CLIPS> (defrule no-emergency
(not (emergency))
=> (printout t "no emergency" crlf))
==> Activation 0 no-emergency: f-0,
CLIPS> (assert (emergency (type fire)))
<== Activation 0 no-emergency: f-0,
<Fact-1>
CLIPS>

Expert Systems: Principles and Programming, Fourth Edition 66


The Exists Conditional Element

• The exists CE allows one to pattern match based


on the existence of at least one fact that matches
a pattern without regard to the total number of
facts that actually match the pattern.
• This allows a single partial match or activation
for a rule to be generated based on the existence
of one fact out of a class of facts.

Expert Systems: Principles and Programming, Fourth Edition 67


Exists Conditional

Expert Systems: Principles and Programming, Fourth Edition 68


Exists
• When more than one emergency fact is asserted, the
message to the operators is printed more than once. The
following modification prevents this:

Expert Systems: Principles and Programming, Fourth Edition 69


Exists
• This assumes there was already an alert – triggered by
an operator-emergency rule. What if the operators were
merely placed on alert to a drill:
(defrule operator-alert-for-drill
(operator-drill)
(not (operator-alert))
=>
(printout t “Drill: Operator Alert” crlf)
(assert (operator-alert)))
• If this rule fires first, then the emergency alert rule will
never fire later because (operator-alert) is asserted.

Expert Systems: Principles and Programming, Fourth Edition 70


Exists
• Now consider how the rule has been modified
using the exists CE:
(defrule operator-alert-for-emergency
(exists (emergency))
=>
(printout t “Emergency: Operator Alert” crlf)
(assert (operator-alert))))

Expert Systems: Principles and Programming, Fourth Edition 71


Forall / Logical
Conditional Elements
• The forall CE allows one to pattern match based
on a set of CEs that are satisfied for every
occurrence of another CE.

• The logical CE allows one to specify that the


existence of a fact depends on the existence of
another fact or group of facts.

Expert Systems: Principles and Programming, Fourth Edition 72


Forall / Logical
Conditional Elements
(deftemplate emergency
(slot type)
(slot location))

(deftemplate fire-squad
(slot name
(slot location))

(deftemplate evacuated
(slot building))

Expert Systems: Principles and Programming, Fourth Edition 73


Forall / Logical
Conditional Elements
(defrule all-fires-being-handled
(forall (emergency (type fire)
(location ?where))
(fire-squad (location ?where))
(evacuated (building ?where)))
=>
(printout t “All buildings that are on fire have
been evacuated” crlf))

• For every fact that matches the (emergency (type fire) (location ?
where)) pattern, there must also be facts matching the (fire-
squad (location ?where)) pattern and the (evacuated (building ?
where)) pattern.

Expert Systems: Principles and Programming, Fourth Edition 74


Forall / Logical
Conditional Elements
(defrule (noxious-fumes-present
(logical (emergency (type fire))
(noxious-fumes-present)
=>
(assert (use-oxygen-masks))))

• When the noxious-fumes-present rule is executed, a link is


created between the facts matching the patterns contained
within the logical CE in the LHS of a rule and the facts
asserted from the RHS of the rule  if either of the facts is
retracted (emergency or noxious-fumes-present), then the
use-oxygen-masks rule will also be retracted.

Expert Systems: Principles and Programming, Fourth Edition 75


Summary
• We have introduced the concept of field
constraints – not, and, and or.
• Functions are entered into CLIPS top-level
command loop or are used on the LHS or RHS of
a rule.
– Many functions have variable number of arguments
– Function calls can be nested w/in other function calls

Expert Systems: Principles and Programming, Fourth Edition 76


Summary
• CLIPS provides several I/O functions.
– Open / close
– Printout / read / readline
– Format
• Various concepts for controlling the flow of
execution are available
• Also included in the discussion were the
following CEs:
– Test, And, Or, Exists, Forall, and logical

Expert Systems: Principles and Programming, Fourth Edition 77

You might also like