Created
June 21, 2024 19:50
-
-
Save mrrodriguez/87053edaca5ae4b3c547303bb49e77f9 to your computer and use it in GitHub Desktop.
Using unconditional-insert! with retract! in a high :salience (initialization) rule
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(require '[clara.rules :as r]) | |
(require '[clara.rules.accumulators :as acc]) | |
(defrecord ExternalFact [id code]) | |
(defrecord DerivedFact [ids]) | |
(r/defrule match-and-remove-it | |
{:salience 1000000} | |
[?fact <- ExternalFact (= ?id id) (= code "a")] | |
=> | |
(r/insert-unconditional! (->DerivedFact [?id])) | |
(r/retract! ?fact)) | |
(r/defquery find-derived [] | |
[?facts <- (acc/all) :from [DerivedFact]]) | |
(r/defquery find-external [] | |
[?facts <- (acc/all) :from [ExternalFact]]) | |
(comment | |
(let [facts [(->ExternalFact 1 "a") | |
(->ExternalFact 2 "b") | |
(->ExternalFact 3 "a")] | |
session (-> (r/mk-session [match-and-remove-it find-derived find-external]) | |
(r/insert-all facts) | |
r/fire-rules)] | |
{:derived (r/query session find-derived) | |
:external (r/query session find-external)}) | |
;;= | |
;; {:derived ({:?facts [#clara.test_rules.DerivedFact{:ids [1]} #clara.test_rules.DerivedFact{:ids [3]}]}), | |
;; :external ({:?facts [#clara.test_rules.ExternalFact{:id 2, :code "b"}]})} | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment