Skip to content
Baptiste Fontaine edited this page Feb 1, 2018 · 5 revisions

Clara's accumulators are designed to compute a summary over a collection of matched facts. Examples include:

  • Identifying the minimum or maximum of a value
  • Performing a summarization, such as an average or histogram
  • Perform some arbitrary transformation or selection of data for a domain-specific need.

Accumulators are implemented using Clojure's reducers library. An accumulator is defined by four parts:

  • reduce-fn - A reduce function, in the style of clojure.core.reducers, which reduces a collection of values into a single output
  • combine-fn - A combine function, in the style of clojure.core.reducers, which combines the outputs of two reduce-fn operations into a new, single output.
  • initial-value - an optional parameter that will be passed to the reduce-fn if provided
  • retract-fn - An optional function that accepts a previously reduced output and a fact, and returns a new reduced output with the given fact retracted.
  • convert-return-fn - an operation that performs some conversion on the reduce/combine value before returning it to the caller

Accumulators can be created with the accumulate function in the clara.rules namespace. A set of common accumulators is also pre-defined for convenience.

Here's an example of an accumulator in action:

;; Creates an accumulator that selects the item with the newest timestamp field.
(def newest-temp (acc/max :timestamp :returns-fact true))

(defrule get-current-temperature
  [?current-temp <- newest-temp :from [Temperature (== ?location location)]]
  =>
  ; Do something.
  )

Resources

Clone this wiki locally