首页 > 解决方案 > 如何以面向对象的方式对事实建模?

问题描述

我喜欢剪辑,并且很乐意用它来定义规则,我想将它用于即将到来的项目。但是,我需要对 XML 文件执行一些规则。我有一堆 XML,我需要从中提取一些输出和见解。我想在这里寻求指导,是否有任何模式可以将对象建模为剪辑事实?


考虑以下示例:

<families>
    <family>
        <children>
            <boy age="11"/>
            <girl age="12"/>
        </children>
        <parent>
            <father age="31"/>
            <mother age="29"/>
        </parent>
    </family>
</families>

我如何将其转换为剪辑中的事实,并编写一条规则来输出母亲比父亲大的男孩的数量?

谢谢,

标签: clips

解决方案


使用对象而不是事实会更好,因为您可以利用继承,但是您可以通过为每个事实分配一个名称来使用事实来实现这一点,并将其用作符号链接来表示 XML 的嵌套结构:

         CLIPS (6.31 6/12/19)
CLIPS>    
(deftemplate family
   (slot name)
   (slot progenitor (default none))
   (multislot children)
   (multislot parent))
CLIPS>       
(deftemplate boy
   (slot name)
   (slot progenitor (default none))
   (slot age))
CLIPS>    
(deftemplate girl
   (slot name)
   (slot progenitor (default none))
   (slot age))
CLIPS>    
(deftemplate father
   (slot name)
   (slot progenitor (default none))
   (slot age))
CLIPS> 
(deftemplate mother
   (slot name)
   (slot progenitor (default none))
   (slot age))
CLIPS>    
(deffacts data
   (boy-count)
   (family (name family-1)
           (children boy-1 girl-1)
           (parent father-1 mother-1))
   (boy (name boy-1)
        (progenitor family-1)
        (age 11))
   (girl (name girl-1)
         (progenitor family-1) 
         (age 13)) 
   (father (name father-1)
           (progenitor family-1)
           (age 31))
   (mother (name mother-1)
           (progenitor family-1) 
           (age 29))      
   (family (name family-2)
           (children boy-2 boy-3)
           (parent father-2 mother-2))
   (boy (name boy-2)
        (progenitor family-2)
        (age 14))
   (boy (name boy-3)
        (progenitor family-2) 
        (age 16)) 
   (father (name father-2)
           (progenitor family-2)
           (age 35))
   (mother (name mother-2)
           (progenitor family-2) 
           (age 43)))
CLIPS>              
(defrule add-boy
   (family (name ?family))
   (father (age ?fa) (progenitor ?family))
   (mother (age ?ma&:(> ?ma ?fa)) (progenitor ?family))
   (boy (name ?boy) (progenitor ?family))
   ?bc <- (boy-count $?names&:(not (member$ ?boy ?names)))
   =>
   (retract ?bc)
   (assert (boy-count ?names ?boy)))
CLIPS> 
(defrule print-count
   (declare (salience -10))
   (boy-count $?names)
   =>
   (bind ?count (length$ ?names))
   (switch ?count
      (case 0 then (printout t "There are no boys"))
      (case 1 then (printout t "There is 1 boy"))
      (default then (printout t "There are " ?count " boys")))
   (printout t " with a mother older than a father." crlf))
CLIPS> (reset)
CLIPS> (run)
There are 2 boys with a mother older than a father.
CLIPS> 

推荐阅读