Search code examples
clipsexpert-system

Find best rule matched in clips


I am new to CLIPS and during the development of a personal project, I would like to implement a functionality that will allow me to see the rules having the most patterns matched after a fact insertion. For a better comprehension :

>(defrule one
        (fact a)
        (fact b)
=>
        (assert (fact i)))

>(defrule two
        (fact b)
        (fact c)
=>
        (assert (fact d) (fact f)))

>(defrule three
        (fact a)
        (fact d)
        (fact c)
=>
        (assert (fact g)))


> (assert (fact a) (fact c))
> (trace-rule)
rule three 
Matches for Pattern 1
f-1
Matches for Pattern 2
None
Matches for Pattern 3
f-2

Maybe I could use matches command but I don't know how to proceed.

Thanks for your time.


Solution

  •          CLIPS (6.30 3/17/15)
    CLIPS> 
    (deffunction most-matches ()
       (bind ?rules (create$))
       (bind ?most -1)
       (foreach ?r (get-defrule-list)
          (bind ?matches (nth$ 1 (matches ?r terse)))
          (if (= ?matches ?most)
             then
             (bind ?most ?matches)
             (bind ?rules (create$ ?rules ?r))
             else
             (if (> ?matches ?most)
                then
                (bind ?most ?matches)
                (bind ?rules (create$ ?r)))))
       ?rules)
    CLIPS>    
    (defrule one
       (fact a)
       (fact b)
       =>
       (assert (fact i)))
    CLIPS> 
    (defrule two
       (fact b)
       (fact c)
       =>
       (assert (fact d)
               (fact f)))
    CLIPS> 
    (defrule three
       (fact a)
       (fact d)
       (fact c)
       =>
       (assert (fact g)))
    CLIPS> (assert (fact a) (fact c))
    <Fact-2>
    CLIPS> (most-matches)
    (three)
    CLIPS> (reset)
    CLIPS> (assert (fact b))
    <Fact-1>
    CLIPS> (most-matches)
    (one two)
    CLIPS> (reset)
    CLIPS> (most-matches)
    (one two three)
    CLIPS>