There is a query function for checking the contents of the clara-rules session from the outside, so I tried to find out how to use it.
--Basically, only the left side of the rule is defined.
--Rules are used to derive new facts from existing facts added to the session --Query is used purely to look inside the session --Debug --Intermediate step to extract information from the calculated session and pass it to another process
(ns clara-rules.join
(:require [clara.rules :refer [defrule fire-rules insert
mk-session query defquery]]))
(defrecord TypeA [attr-a join-key])
(defrecord TypeB [attr-b join-key])
;;Queries
(defquery find-all-As
[];;parameters
[?a <- TypeA];;Matching condition
)
(defquery find-As-by-attr
[:?value];; Parameter needs to be a keyword
[?a <- TypeA (= attr-a ?value)])
(defquery find-join-key-of-As
[]
[TypeA (= ?jk join-key)])
(defquery find-A-and-B-pair-by-join-key
[:?value]
[?a <- TypeA (= join-key ?value)]
[?b <- TypeB (= join-key ?value)])
(def sess (-> (mk-session)
(insert (->TypeA "a1" :foo)
(->TypeA "a2" :bar)
(->TypeA "a3" :baz)
(->TypeB "b1" :foo)
(->TypeB "b2" :bar)
(->TypeB "b3" :baz)
(->TypeB "b4" :qux))
(fire-rules)))
(query sess find-all-As)
;; ({:?a {:attr-a "a1", :join-key :foo}}
;; {:?a {:attr-a "a2", :join-key :bar}}
;; {:?a {:attr-a "a3", :join-key :baz}})
(query sess find-As-by-attr :?value "a1")
;; => ({:?a #clara_rules.join.TypeA{:attr-a "a1", :join-key :foo}, :?value "a1"})
(query sess find-join-key-of-As)
;; => ({:?jk :foo} {:?jk :bar} {:?jk :baz})
(query sess find-A-and-B-pair-by-join-key :?value :foo)
;; => ({:?a {:attr-a "a1", :join-key :foo},
;; :?value :foo,
;; :?b {:attr-b "b1", :join-key :foo}})
--defquery
can be written in the same way as the left side of defrule
, except that parameters can be received externally.
--Variable binding etc
--query
returns the variable bound in defquery
as the key of the resulting map
--query
returns the match as a sequence of maps
In the previous examples, the side effect (println) was only used on the right side of the rule to check the result. I'm glad that I was able to solve one of the questions I had since I touched on whether there was a way to check the results without using side effects.
Recommended Posts