Search code examples
clips

how to get the objects in clips in order on LHS side based on a particular slot in class


Is there any way to get the objects in clips in order on LHS side based on a particular slot in class?

(defclass SAMPLE
    "all the information about students"
    (is-a BASE_SAMPLE) (role concrete) (pattern-match reactive)
    (slot ID   (create-accessor read-write) (access initialize-only) (propagation inherit) (visibility public) (type INTEGER))
    (slot NAME  (create-accessor read-write) (access initialize-only) (propagation inherit) (visibility public) (type STRING))
)

if I have 100 SAMPLE objects, and I want all of them to come in ascending order based on the slot ID on the LHS of a rule, is this poosilbe in clips?


Solution

  • There's two ways you can sort the objects. You can do it on the LHS by adding some additional information to either the objects or a separate fact/instance to retain information on which objects have been processed:

    CLIPS> (clear)
    CLIPS>    
    (defclass STUDENT
       (is-a USER)
       (slot id)
       (slot full-name)
       (slot processed (default no)))
    CLIPS>    
    (definstances people
       (of STUDENT (id 102) (full-name "Fred Jones"))
       (of STUDENT (id 438) (full-name "Sally Smith"))
       (of STUDENT (id 391) (full-name "John Farmer")))
    CLIPS> 
    (defrule list 
       ?i <- (object (is-a STUDENT)
                     (id ?id1)
                     (processed no))
             (not (object (is-a STUDENT)
                          (id ?id2&:(> ?id1 ?id2))
                          (processed no)))
       =>
       (modify-instance ?i (processed yes))
       (printout t ?id1 " " (send ?i get-full-name) crlf))
    CLIPS> (reset)
    CLIPS> (run)
    102 Fred Jones
    391 John Farmer
    438 Sally Smith
    CLIPS> 
    

    Or you can sort the values on the RHS:

    CLIPS> (clear)
    CLIPS> 
    (defclass STUDENT
       (is-a USER)
       (slot id)
       (slot full-name))
    CLIPS>    
    (definstances students
       (of STUDENT (id 102) (full-name "Fred Jones"))
       (of STUDENT (id 438) (full-name "Sally Smith"))
       (of STUDENT (id 391) (full-name "John Farmer")))
    CLIPS>    
    (deffunction id-sort (?i1 ?i2)
       (> (send ?i1 get-id) (send ?i2 get-id)))
    CLIPS>    
    (defrule list
       =>
       (bind ?instances (find-all-instances ((?i STUDENT)) TRUE))
       (bind ?instances (sort id-sort ?instances))
       (progn$ (?i ?instances)
          (printout t (send ?i get-id) " " (send ?i get-full-name) crlf)))
    CLIPS> (reset)
    CLIPS> (run)
    102 Fred Jones
    391 John Farmer
    438 Sally Smith
    CLIPS>