16.8.2. Bound variables in patterns and constraints
You can bind variables to patterns and constraints to refer to matched objects in other portions of a rule. Bound variables can help you define rules more efficiently or more consistently with how you annotate facts in your data model. To differentiate more easily between variables and fields in a rule, use the standard format $variable for variables, especially in complex rules. This convention is helpful but not required in DRL.
For example, the following DRL rule uses the variable $p for a pattern with the Person fact:
Pattern with a bound variable
rule "simple rule"
when
$p : Person()
then
System.out.println( "Person " + $p );
end
Similarly, you can also bind variables to properties in pattern constraints, as shown in the following example:
// Two persons of the same age:
Person( $firstAge : age ) // Binding
Person( age == $firstAge ) // Constraint expression
Ensure that you separate constraint bindings and constraint expressions for clearer and more efficient rule definitions. Although mixed bindings and expressions are supported, they can complicate patterns and affect evaluation efficiency.
// Do not use the following format:
Person( $age : age * 2 < 100 )
// Use the following format instead:
Person( age * 2 < 100, $age : age )
The decision engine does not support bindings to the same declaration, but does support unification of arguments across several properties. While positional arguments are always processed with unification, the unification symbol := exists for named arguments.
The following example patterns unify the age property across two Person facts:
Example pattern with unification
Person( $age := age )
Person( $age := age )
Unification declares a binding for the first occurrence and constrains to the same value of the bound field for sequence occurrences.