专家系统JESS实例教程

来源:互联网 发布:ubuntu 16.04lts 编辑:程序博客网 时间:2024/04/30 04:43

我们假设有一个交易系统,客户提出要买的东西,卖家提供要买的东西,如果有符合的,就成交。这是一个很简单的系统,用一般程序语言也可以实现,但是我们看看专家系统开发更简单的方法。

1第一条规则

如果来了新的客户,取得这个客户所有需要的商品,并产生新的事实。

(defrule query-buyer
  ?fact <- (new-buyer ?buyer)            ; if there is a new a buyer...
=>
  (retract ?fact)
  (foreach ?i (nth$ 2 (send ?buyer "GetProducts"))
    (assert (requires ?buyer ?i))        ; get the products the buyer requires
                                         ; and for each one create a fact
                                         ; associating the buyer and the product
   )
)

例如,来了一个客户Danny,我们先assert(new-buyer danny) ,jess发现了这条事实后,触发query-buyer这个规则,注意所有的规则之间没有顺序性。query-buyer这条规则先撤销刚才的事实,避免死循环,然后调用一个函数取得用户所有需要的商品Send ?buyer "GetProducts".例如得到的结果是(Computer Keyboard Mouse),然后规则遍历这个结果集,每一个商品都产生一个新的事实,例如assert requires Danny Computer等等。

2 第二个规则,出现一个新卖家,原理和刚才一样

(defrule query-seller
  ?fact <- (new-seller ?seller)          ; if there is a new seller...
=>
  (retract ?fact)
  (foreach ?i (nth$ 2 (send ?seller "GetProducts"))
    (assert (provides ?seller ?i))       ; get the products the seller provides
                                         ; and for each one create a fact
                                         ; associating the seller and the product
   )
)

3 最后一个是交易的规则

当有买家购买一个商品,卖家卖一个商品,并且两者相同的事实时候,告诉卖家有人要买该物品,同时也告诉买家有卖家投递该物品

(defrule match-buyer-and-seller
  (requires ?buyer ?product1)            ; the buyer requires product1
  (provides ?seller ?product2)           ; the seller provides product2
  (test (eq ?product1 ?product2))        ; product1 and product2 are the same
=>
  (send ?seller "Order" ?product2)       ; order from the seller
  (send ?buyer "Delivery" ?product1)     ; deliver to the buyer
)

从这个规则中,我们看到,实现这样一个交易市场的系统,没有任何遍历所有买家和卖家进行比较的操作。这些匹配是JESS自动模式匹配完成的,大大简化了开发。

使用专家系统,我们可以通过定义规则的方式来积累经验,而不是通过If else这样的代码来积累经验。



Trackback: http://tb.blog.csdn.net/TrackBack.aspx?PostId=531463


原创粉丝点击