You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在CLIPS中累加同类型事实的槽位值并归集说明信息?

CLIPS 按类型累加事实槽值并收集多槽内容

需求说明

我定义了以下两个deftemplate:

(deftemplate effect (slot type) (slot value) (slot explanation))
(deftemplate result (slot type) (slot total_value) (multislot total_explanation))

以及对应的deffacts:

(effect (type A) (value 1) (explanation "A is 1"))
(effect (type A) (value 2) (explanation "A is 2"))
(effect (type B) (value 3) (explanation "B is 3"))
(effect (type B) (value 4) (explanation "B is 4"))

希望实现按type对同类型的effect事实累加value总和,同时收集所有对应的explanation到result的多槽,最终得到:

(result (type A) (total_value 3) (total_explanation "A is 1" "A is 2"))
(result (type B) (total_value 7) (total_explanation "B is 3" "B is 4"))

我尝试了以下代码,但无法正确运行:

(defrule accumulate_typeA
(exists (effect (type A)))
=>
(bind ?sum 0)
(do-for-all-facts ((?f effect) (bind ?sum (+ ?sum ?f:value))
(bind ?expl (create$))
(do-for-all-facts ((?f effect) (bind ?expl (inserts ?f:explanation)))) 
(assert (result (type A) (total_value ?sum) (total_explanation ?expl))

问题分析与修正方案

你写的代码存在语法和逻辑问题:

  • do-for-all-facts语法错误:缺少必要括号、过滤条件,且inserts是错误函数,应使用create$或insert$。
  • 仅能处理type A,无法通用适配所有类型。

正确实现代码

方案1:通用处理所有type的规则

(defrule accumulate-by-type
    ; 匹配一个未生成对应result的effect类型
    (effect (type ?type))
    (not (result (type ?type)))
=>
    (bind ?sum 0)
    (bind ?expl-list (create$))
    ; 遍历同类型的所有effect事实
    (do-for-all-facts ((?f effect)) (eq ?f:type ?type)
        (bind ?sum (+ ?sum ?f:value))
        (bind ?expl-list (create$ ?expl-list ?f:explanation))
    )
    ; 生成对应的result事实
    (assert (result (type ?type) (total_value ?sum) (total_explanation ?expl-list)))
)

方案2:单独处理指定类型(如仅处理type A)

(defrule accumulate_typeA
    (exists (effect (type A)))
    (not (result (type A)))
=>
    (bind ?sum 0)
    (bind ?expl (create$))
    (do-for-all-facts ((?f effect)) (eq ?f:type "A")
        (bind ?sum (+ ?sum ?f:value))
        (bind ?expl (create$ ?expl ?f:explanation))
    )
    (assert (result (type A) (total_value ?sum) (total_explanation ?expl)))
)

代码说明

  • do-for-all-facts的第二个参数是过滤条件,确保仅处理当前type的事实。
  • create$用于创建或扩展多槽列表,将每个explanation追加到列表中。
  • 添加(not (result (type ?type)))条件,避免重复生成相同的result事实。
  • 通用方案会自动适配所有存在的type,无需为每个类型单独编写规则。

内容的提问来源于stack exchange,提问作者dokgom

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.07 03:35:21