next up previous

5.4.1.5 Predicate Constraints

Sometimes it becomes necessary to constrain a field based upon the truth of a given boolean expression. CLIPS allows the use of a predicate constraint to restrict a field in this manner. The predicate constraint allows a predicate function (one returning the symbol FALSE for unsatisfied and a nonFALSE value for satisfied) to be called during the patternmatching process. If the predicate function returns a nonFALSE value, the constraint is satisfied. If the predicate function returns the symbol FALSE, the constraint is not satisfied. A predicate constraint is invoked by following a colon with an appropriate function call to a predicate function. Typically, predicate constraints are used in conjunction with a connective constraint and a variable binding (i.e. you have to bind the variable to be tested and then connect it to the predicate constraint).

Basic Syntax

:<function-call>

Syntax

Expanding on the syntax definition given in section 5.4.1.4 now gives:

<term> ::= <constant> |
           <single-field-variable> |
           <multifield-variable> |
           :<function-call>

Multiple predicate constraints may be used to constrain a single field. Several predicate functions are provided by CLIPS (see section 12.2). Users also may develop their own predicate functions.

Example 1

CLIPS> (clear)
CLIPS>
(defrule example-1
  (data ?x&:(numberp ?x))
  =>)
CLIPS> (assert (data 1) (data 2) (data red))
<Fact-2>
CLIPS> (agenda)
0      example-1: f-1
0      example-1: f-0
For a total of 2 activations.
CLIPS>

Example 2

CLIPS> (clear)
CLIPS>
(defrule example-2
  (data ?x&~:(symbolp ?x))
  =>)
CLIPS> (assert (data 1) (data 2) (data red))
<Fact-2>
CLIPS> (agenda)
0      example-2: f-1
0      example-2: f-0
For a total of 2 activations.
CLIPS>

Example 3

CLIPS> (clear)
CLIPS>
(defrule example-3
  (data ?x&:(numberp ?x)&:(oddp ?x))
  =>)
CLIPS> (assert (data 1) (data 2) (data red))
<Fact-2>
CLIPS> (agenda)
0      example-3: f-0
For a total of 1 activation.
CLIPS>

Example 4

CLIPS> (clear)
CLIPS>
(defrule example-4
  (data ?y)
  (data ?x&:(> ?x ?y))
  =>)
CLIPS> (assert (data 3)  ; f-0
               (data 5)  ; f-1
               (data 9)) ; f-2
<Fact-2>
CLIPS> (agenda)
0      example-4: f-0,f-2
0      example-4: f-1,f-2
0      example-4: f-0,f-1
For a total of 3 activations.
CLIPS>

Example 5

CLIPS> (clear)
CLIPS>
(defrule example-5
  (data $?x&:(> (length$ ?x) 2))
  =>)
CLIPS> (assert (data 1)      ; f-0
               (data 1 2)    ; f-1
               (data 1 2 3)) ; f-2
<Fact-2>
CLIPS> (agenda)
0      example-5: f-2
For a total of 1 activation.
CLIPS>


next up previous