Fork me on GitHub
#clara
<
2016-11-30
>
wparker13:11:28

I think comparing the result of queries, which will reflect the state of the session before and after you fire rules, is what you’re looking for. So if you have something like

wparker13:11:04

(defrule lousy-weather-rule [?c <- Cold] => (insert! (->LousyWeather)))

wparker13:11:31

(defquery lousy-weather-query “” [] [LousyWeather])

wparker13:11:54

Then (def empty-session (mk-session [lousy-weather-rule lousy-weather-query]))

wparker13:11:08

(query empty-session lousy-weather-query) will return nothing

wparker13:11:33

However, (def not-empty-session (-> empty-session (insert (->Cold)) fire-rules))

wparker13:11:57

(query not-empty-session lousy-weather-query) would find a LousyWeather fact

wparker13:11:35

You could query both before and after inserting/retracting + firing rules afterward and see what changed, then dispatch on that

wparker13:11:59

One perhaps non-obvious part of this is when you query the session, you’re not actually performing much work since Clara basically computes the results for queries after fire-rules. When you run a query you’re really basically retrieving the results already computed with a little data manipulation to get just the bindings you use in your query. You can see that implementation at https://github.com/cerner/clara-rules/blob/0.13.0-RC4/src/main/clojure/clara/rules/engine.cljc#L1605

wparker13:11:08

Basically a query and a rule look the same to the rules engine mostly when you look at determine what facts match, a rule just does more things (i.e. it is activated and can insert more facts) once you find matches

wparker13:11:22

You can think of it as large trees of the different node types in engine.cljc where ProductionNode corresponds to rules, QueryNode corresponds to queries, facts are given to the root nodes of these trees and passed down to the leaf nodes, which are ProductionNodes and QueryNodes

wparker13:11:51

Just comparing the results before and after for the queries would work, albeit somewhat inefficiently since you’d be performing work even when nothing at all changed. I think there are ways Clara could return changes in queries more efficiently than that if you were interested in contributing an enhancement like that though.

nlessa14:11:26

Thank you very much @wparker. Based in your answer I will try some approaches and let you know what I got.