What's the best way to encode a fact that's needed in the RHS but is not important
in the LHS?
Consider a contrived example of computing total household income for single or married
persons. I can think of two ways to encode this rule, but I don't like either of
them:
Style 1: one rule for each scenario
rule "household income, single"
when
$p1 : Person()
not Relation(person1 == $p1, type == "spouse")
then
insertLogical(new Income($p1.getIncome()));
end
rule "household income, married"
when
$p1 : Person()
Relation(person1 == $p1, type == "spouse", $p2: person2)
then
insertLogical(new Income($p1.getIncome() + $p2.getIncome()));
end
Style 2: a single rule with a collection
rule "household income "
when
$p1 : Person()
$rels : List() from collect(Relation($p1 == person1, type ==
"spouse"))
then
insertLogical(new Income($p1.getIncome() + ($rels.size() == 0 ? 0 :
$rels.get(0).getPerson2().getIncome()));
end
(please ignore the bug that the income may get inserted twice because people are spouses
of each other)
Style 1 is more verbose, but more straightforward: it's how I think of the problem
intuitively. Style 2 is much more compact, and is more maintainable if I need to add more
predicates or a more complicated RHS. But the idea of needing a List when I know there
will be exactly 0 or 1 related facts just seems wrong.
I've searched for some LHS syntax that assigns a variable without participating in
boolean evaluation, but I've failed to find anything.
Chris