Following the previous article, I will describe an implementation using the Clara Rule, an expert system in Clojure, based on the code in “The world of clara-rules” written by iku00088 in 2017. The simplest working code is as follows.
(defrecord Num [number])
(defrule is-two
[Num (= number 2)] => (println "Two!"))
(-> (mk-session)
(insert (->Num 2))
(fire-rules))
;;-> "Two!"
The following is a sample code for a more specific use case (determining whether or not to change a certain product (Item) with money (MyMoney). The final price of the item is determined by the discount rate and tax (rule)).
(def discounted-items #{:fish :pants})
(def tax-rates {:food 0.1 :cloth 0.2 :alcohol 0.3})
(defrecord MyMoney [amt])
(defrecord Tax [category rate])
(defrecord Item [id price category])
(defrecord DiscountedItem [discounted-price category])
(defrecord TaxedItem [final-price])
(defrule DiscountItem
[Item (= ?id id) (= ?category category) (= ?price price)]
=>
(println "Item is" ?id)
(println "Original Price is" ?price)
(println "Discounted item?" (some? (discounted-items ?id)))
(insert! (->DiscountedItem (* ?price 0.9) ?category)))
(defrule TaxItem
[DiscountedItem (= ?category category) (= ?discounted-price discounted-price)]
=>
(println "Tax rate is " (?category tax-rates))
(insert! (->TaxedItem (+ ?discounted-price (* ?discounted-price (?category tax-rates))))))
(defrule EnoughMoney
[MyMoney (= ?amt amt)]
[TaxedItem (= ?final-price final-price) (> ?amt final-price)]
=>
(println "Final price:" ?final-price)
(println "You have enough money!"))
(defrule NotEnoughMoney
[MyMoney (= ?amt amt)]
[TaxedItem (= ?final-price final-price) (not (> ?amt final-price))]
=>
(println "Final price:" ?final-price)
(println "You do not have enough money!"))
(-> (mk-session)
(insert (->MyMoney 199) (->Item :fish 200 :food))
(fire-rules))
;;Item is :fish
;;Original Price is 200
;;Discounted item? true
;;Discounted Price 180.0
;;Tax rate is 0.1
;;Final price: 198.0
;;You have enough money!
Next time, we will take a more flexible approach. We will discuss the case of automatic rule generation from natural text.
コメント