Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save mrrodriguez/87053edaca5ae4b3c547303bb49e77f9 to your computer and use it in GitHub Desktop.
Save mrrodriguez/87053edaca5ae4b3c547303bb49e77f9 to your computer and use it in GitHub Desktop.
Using unconditional-insert! with retract! in a high :salience (initialization) rule
(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