CLIPS技术咨询:如何用defrule批量打印数据及多条件查询?
CLIPS茉莉查询项目问题解决方案
问题1:一次性打印所有茉莉数据解决方案
要实现一次性打印所有茉莉品种的完整数据,可通过CLIPS的do-for-all-facts函数遍历所有jazmin类型事实,结合规则触发打印操作。
实现代码
; 触发打印操作的输入规则 (defrule trigger-print-all => (printout t "输入'print-all'可查看所有茉莉品种: ") (bind ?input (read)) (if (eq ?input "print-all") then (assert (print-all)) ) ) ; 打印所有茉莉数据的核心规则 (defrule print-all-jazmines (print-all) => (printout t "=== 所有茉莉品种列表 ===" crlf) (do-for-all-facts ((?j jazmin)) TRUE (printout t "名称: " ?j:nombre " | 花色: " ?j:color-flor " | 花期: " ?j:floracion crlf) ) (retract (print-all)) )
使用时,用户输入print-all后执行(run),即可触发规则一次性输出所有茉莉品种的详细信息。
问题2:单次run中支持多个查询条件解决方案
要在单次(run)操作中支持多花色、多花期的组合查询,需要调整事实结构和规则匹配逻辑,允许用户输入多个条件值并匹配任一符合条件的品种。
修改后的完整代码
(deftemplate jazmin (slot nombre) (slot color-flor (allowed-values blanca amarilla)) (multislot floracion (allowed-values invierno primavera verano otono)) ) ; 支持多花色输入的规则 (defrule in-color-flor => (printout t "输入花色(可多个,用空格分隔,可选值:blanca amarilla): ") (assert (color-flor $?(readline))) ) ; 支持多花期输入的规则 (defrule in-floracion => (printout t "输入花期(可多个,用空格分隔,可选值:invierno primavera verano otono): ") (assert (floracion $?(readline))) ) ; 多条件匹配查询规则 (defrule buscar-jazmin (color-flor $?colors) (floracion $?seasons) (jazmin (nombre ?nombre) (color-flor ?c) (floracion $? ?s $?)) (test (or (member$ ?c $?colors) (member$ ?s $?seasons))) => (printout t "匹配的茉莉品种: " ?nombre " | 花色: " ?c " | 花期: " ?s crlf) ) ; 无匹配结果提示规则 (defrule jazmin-no-encontrado (color-flor $?colors) (floracion $?seasons) (not (jazmin (nombre ?nombre) (color-flor ?c) (floracion $? ?s $?) (test (or (member$ ?c $?colors) (member$ ?s $?seasons))))) => (printout t "没有找到匹配条件的茉莉品种" crlf) ) ; 保留打印所有数据的规则(同问题1) (defrule trigger-print-all => (printout t "输入'print-all'可查看所有茉莉品种: ") (bind ?input (read)) (if (eq ?input "print-all") then (assert (print-all)) ) ) (defrule print-all-jazmines (print-all) => (printout t "=== 所有茉莉品种列表 ===" crlf) (do-for-all-facts ((?j jazmin)) TRUE (printout t "名称: " ?j:nombre " | 花色: " ?j:color-flor " | 花期: " ?j:floracion crlf) ) (retract (print-all)) ) (deffacts jazmines (jazmin (nombre Jazmin-Blanco) (color-flor blanca) (floracion primavera verano otono)) (jazmin (nombre Jazmin-Chino) (color-flor blanca) (floracion primavera)) (jazmin (nombre Jazmin-Silvestre) (color-flor amarilla) (floracion verano)) (jazmin (nombre Jazmin-Azor) (color-flor blanca) (floracion primavera)) (jazmin (nombre Jazmin-Espanol) (color-flor blanca) (floracion verano otono)) (jazmin (nombre Jazmin-Amarillo) (color-flor amarilla) (floracion invierno primavera)) )
关键修改说明
- 输入规则使用
readline读取用户输入的多个条件值,存入multislot类型的事实中; - 查询规则通过
test条件判断,只要茉莉品种的花色属于用户输入的花色列表,或花期属于用户输入的花期列表,即视为匹配; - 单次
(run)即可完成多条件组合查询,无需多次执行命令。
内容的提问来源于stack exchange,提问作者Manuel Villanueva
相关产品推荐
相关产品推荐

