如何获得多插槽中的项目总和

时间:2019-03-18 09:14:35

标签: clips

我有一个像下面所示的模板。如何获得多插槽等级中的项目总数?

(deftemplate student
  (multislot name)
  (multislot grades)
)

2 个答案:

答案 0 :(得分:2)

这是一种方法。在reg6规则中,为确保+函数允许至少具有2个参数,除等级外,+函数还给两个参数0赋值。否则,如果该学生的成绩为零或一,就会出错。

         CLIPS (6.31 2/3/18)
CLIPS> 
(deftemplate student
  (multislot name)
  (multislot grades))
CLIPS> 
(deftemplate sum
   (multislot name)
   (slot grade))
CLIPS>    
(defrule reg6
   (student (name $?name)
            (grades $?grades))
   =>
   (assert (sum (name ?name)
                (grade (+ 0 0 (expand$ ?grades))))))
CLIPS> 
(assert (student (name David Green) (grades))
        (student (name Sue Brown) (grades 90))
        (student (name Frank Black) (grades 85 75)))
<Fact-3>
CLIPS> (run)
CLIPS> (facts)
f-0     (initial-fact)
f-1     (student (name David Green) (grades))
f-2     (student (name Sue Brown) (grades 90))
f-3     (student (name Frank Black) (grades 85 75))
f-4     (sum (name Frank Black) (grade 160))
f-5     (sum (name Sue Brown) (grade 90))
f-6     (sum (name David Green) (grade 0))
For a total of 7 facts.
CLIPS> 

答案 1 :(得分:1)

您可以使用expand$功能。进入Basic Programming Guide Multifield Expansion Function一章,了解更多信息。

(deftemplate student 
  (multislot name) 
  (multislot grades))  

(defrule grades-sum 
  (student (grades $?grades)) 
  => 
  (printout t "Student grades sum is " (+ (expand$ ?grades)))) 

(assert (student (grades (create$ 1 2 3 4 5)))) 
(student (name) (grades 1 2 3 4 5))

(run)       
Student grades sum is 15