Search code examples
rulesrule-engineclipclips

Firing rule in Clips not working properly


I am new ti clips and is trying to write the rules for triggering a set of rule. the condition for rule is

Calculate the discount of products of product 1, product 2, product 3 as 10, only if product 1 is present(mandatory). and the total quantity of products is greater than or equal to 6.

(deftemplate Product
   (slot productNumber)
   (slot quantity))

(defrule sum_of_quantity
   (exists (Product (productNumber 1 | 2 | 3)(quantity ?q&:(> ?q 1))))
   =>
   (bind ?totalQuantity 0)
   (do-for-all-facts ((?p Product))
                     (or (eq ?p:productNumber 1)
                         (eq ?p:productNumber 2)
                         (eq ?p:productNumber 3))
      (bind ?totalQuantity (+ ?totalQuantity ?p:quantity)))
   (if (>= ?totalQuantity 6) then
      (printout t "TotalQuantity is " ?totalQuantity "and discoun is 10" crlf)))

(deffacts input1 
   (Product (productNumber 2)(quantity 3))
   (Product (productNumber 3)(quantity 3)))

The facts was entered as shown and even without the mandatory product the result is computed and shown as 10.

Do suggest.


Solution

  •          CLIPS (6.31 6/12/19)
    CLIPS> 
    (deftemplate Product
       (slot productNumber)
       (slot quantity))
    CLIPS> 
    (defrule sum_of_quantity
       (exists (Product (productNumber 1) (quantity ?q&:(> ?q 1))))
       =>
       (bind ?totalQuantity 0)
       (do-for-all-facts ((?p Product))
                         (or (eq ?p:productNumber 1)
                             (eq ?p:productNumber 2)
                             (eq ?p:productNumber 3))
          (bind ?totalQuantity (+ ?totalQuantity ?p:quantity)))
       (if (>= ?totalQuantity 6) then
          (printout t "TotalQuantity is " ?totalQuantity " and discount is 10" crlf)))
    CLIPS> (assert (Product (productNumber 1) (quantity 6)))
    <Fact-1>
    CLIPS> (run)
    TotalQuantity is 6 and discount is 10
    CLIPS> (reset)
    CLIPS> (assert (Product (productNumber 1) (quantity 3)))
    <Fact-1>
    CLIPS> (assert (Product (productNumber 2) (quantity 2)))
    <Fact-2>
    CLIPS> (assert (Product (productNumber 3) (quantity 4)))
    <Fact-3>
    CLIPS> (run)
    TotalQuantity is 9 and discount is 10
    CLIPS> (reset)
    CLIPS> (assert (Product (productNumber 2) (quantity 2)))
    <Fact-1>
    CLIPS> (assert (Product (productNumber 3) (quantity 4)))
    <Fact-2>
    CLIPS> (run)
    CLIPS>