How can I get the sum of items in a multislot

走远了吗. 提交于 2019-12-13 04:08:21

问题


I have a template like the one shown bellow. How can I get the sum of items in the multislot grades?

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

回答1:


You can use the expand$ function. Check in the Basic Programming Guide the Multifield Expansion Function chapter to know more.

(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



回答2:


Here's one way to do it. In the reg6 rule, the + function is given two arguments of 0 in addition to the grades to insure that the + function allows has at least 2 arguments; otherwise, if there were zero or one grades for the student you'd get an error.

         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> 


来源:https://stackoverflow.com/questions/55217909/how-can-i-get-the-sum-of-items-in-a-multislot

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!