George Tseres
George Tseres

Reputation: 498

Modifying the current fact that fires a rule

Say I have defined a template and some facts as shown below:

(deftemplate student
    (slot name (type SYMBOL) (default ?NONE))
    (slot grade (type SYMBOL) (default C) (allowed-symbols A B C D))
    (slot graduated (type SYMBOL) (default no) (allowed-symbols yes no))
)

(deffacts insert-facts
    (student (name George) (grade A))
    (student (name Nick) (grade C))
    (student (name Bob))
    (student (name Mary) (grade B))
)

Say that I want to create a rule that checks the grade of each student and sets the corresponding graduated variable to the symbol 'yes'. How could I do this?

Upvotes: 1

Views: 2960

Answers (2)

Gary Riley
Gary Riley

Reputation: 10757

Here's a slightly less verbose version of the rule you came up with to solve your problem:

CLIPS> 
(deftemplate student
    (slot name (type SYMBOL) (default ?NONE))
    (slot grade (type SYMBOL) (default C) (allowed-symbols A B C D))
    (slot graduated (type SYMBOL) (default no) (allowed-symbols yes no)))
CLIPS> 
(deffacts insert-facts
    (student (name George) (grade A))
    (student (name Nick) (grade C))
    (student (name Bob))
    (student (name Mary) (grade B)))
CLIPS> 
(defrule rule-1
   ?s <- (student (grade A|B) (name ?n) (graduated ~yes))
   =>
   (modify ?s (graduated yes))
   (printout t "Congratulations " ?n "!" crlf))
CLIPS> (reset)
CLIPS> (run)
Congratulations Mary!
Congratulations George!
CLIPS> 

Upvotes: 3

George Tseres
George Tseres

Reputation: 498

I have solved the problem. I leave it here in case someone else needs it.

I have created the rule in the following way

(defrule rule-1
    ?s <- (student (grade ?g&A|B) (name ?n) (graduated ?gr) (classified ?c&no))
=>
    (retract ?s)
    (assert (student (name ?n)(grade ?g) (graduated yes) (classified yes)))
    (printout t "Congratulations " ?n "!" crlf)
)

And have modified the student template in the following way, in order to prevent the program from falling into an infinite loop.

(deftemplate student
    (slot name (type SYMBOL) (default ?NONE))
    (slot grade (type SYMBOL) (default C) (allowed-symbols A B C D))
    (slot graduated (type SYMBOL) (default no) (allowed-symbols yes no))
    (slot classified (type SYMBOL) (default no) (allowed-symbols yes no))
)

Upvotes: 0

Related Questions