The core of cre is a compact Java library with no dependencies on jaskell. It can be used directly from within Java. It can be downloaded here
In this article I'll describe the basic design of cre.
IRule
First, we need an interface for rules:
- the boolean return value indicates whether the rule is applicable at all. (Certain rule may be only applicable to female, for example)
- the RuleContext is our "facts". Rule objects access this parameter for any external information it needs. (For example, what is today's Nasdaq index?)
- the Variant parameter is a placeholder for the rule's result.
Rule Combinators
In order to make the syntax of combining rules in Java easier, an abstract class Rule is designed with many frequently used combinators pre-defined.
Simple Rule
When defining a simple rule that's always applicable, (to get today's Nasdaq index), the SimpleRule can be inheried. For example:
Non-applicable Rule
Though not-obvious, it is quite important to define a rule that never applies. We call it NA. NA rule will not change the Variant result and simply returns false.
NA rule can be obtained by calling Rules.nil().
A Rule that yields a constant value.
We also need rules that always apply and return a constant value. See Rules.retn and its overloaded version.
The following code creates a Rule object that yields the value 1:
If-Else
Sometimes, we want to evaluate different rule based on a condition. (If the customer is female, then apply female_rule, otherwise male_rule). Using Rules.ifelse, we can implement such composite rule as:
Wait, what if there's no customer defined at all?
Well, in that case, the is_female rule will be non-applicable, so is this myrule.
Defining "applicability"
So how do we define a rule that's only applicable under certain circumstances? We can of course implement the apply() method by returning false appropriately. But that's too procedural. There's a much more elegant way to go - we can use the Rules.ifelse combinator such that:
Alternatively, the Rule class predefined two helper methods that can simplify the syntax to:
or
Mutually exclusive rules
It's very typical to have such requirement that "if rule1 applies, use rule1, otherwise use rule2, rule3 etc until one rule applies". Such requirement can be implemented declaratively by Rules.any()
Others
There are many other combinators available. Please check out the javadoc here for further discussion.
