list - 如何从 CLIPS 的列表中找到最大元素?
问题描述
我正在尝试从列表中找出最大元素,例如
(deffacts list
(list 1 2 3 4 5 6 7 6 5 4 3 2 1))
在剪辑中。我怎样才能做到这一点,以一种非常简单的方式,在 derule 中?
另外,如果我有一个病人模板,带有以下插槽:
(deftemplate patient
(slot name)
(slot age)
(multislot tens_max)
(multislot tens_min))
(deffacts data_patient
(patient (name John) (age 22) (tens_max 13 15 22 11) (tens_min 6 7 14 6))
)
我想从最后一个多槽中找出最大元素 tens_min,我该怎么做?
我会很感激任何建议。
解决方案
您可以使用max函数来查找其参数的最大值。您可以将数字列表绑定到规则条件中的多字段变量。然而,max函数需要单独的参数,因此您不能只将多字段值传递给它。您可以使用expand$函数将多字段值拆分为函数调用的单独参数。max函数在CLIPS 6.3 中至少需要 2 个参数,在 CLIPS 6.4 中至少需要 1 个参数,因此为了完整起见,您需要处理这些情况。您可以创建一个 deffunction 来处理代码中的这些边缘情况。
CLIPS (6.31 6/12/19)
CLIPS>
(deffunction my-max ($?values)
(switch (length$ ?values)
(case 0 then (return))
(case 1 then (return (nth$ 1 ?values)))
(default (return (max (expand$ ?values))))))
CLIPS>
(deffacts list
(list 1 2 3 4 5 6 7 6 5 4 3 2 1))
CLIPS>
(defrule list-max
(list $?values)
=>
(printout t "list max = " (my-max ?values) crlf))
CLIPS>
(deftemplate patient
(slot name)
(slot age)
(multislot tens_max)
(multislot tens_min))
CLIPS>
(deffacts data_patient
(patient (name John) (age 22) (tens_max 13 15 22 11) (tens_min 6 7 14 6)))
CLIPS>
(defrule patient-max
(patient (tens_min $?values))
=>
(printout t "patient max = " (my-max ?values) crlf))
CLIPS> (reset)
CLIPS> (run)
patient max = 14
list max = 7
CLIPS>