Conditions
Rules can be enriched with conditions in order to constrain specific values for variables of the body.
Syntactically, the conditions follow the body of the rule.
A condition is the comparison (>,<,=,>=,⇐,<>
) of a variable (the LHS of the comparison)
of the body and an expression (the RHS of the comparison).
Notice that although the comparison symbols used in conditions are partially overlapped with the symbols for comparison operators (partially, since we have =
for equality instead of ==
), they have different semantics.
While comparison operators calculate Boolean results, comparison symbols in conditions only specify a filter.
Each rule can have multiple comma-separated conditions.
contract("Mark",14).
contract("Jeff",22).
rich(X) :- contract(X,Y),Y>=20.
@output("rich").
In the example we individuate the contracts for Y>=20 and classify the respective employee as rich. The expected result is:
rich("Jeff").
balanceItem(1,7,2,5).
balanceItem(2,2,2,7).
error(E,I) :- balanceItem(I,X,Y,Z),X<>Y+Z.
@output("error").
In the example we individuate the balance items for which X is different from the sum of Y and Z and report an error E for the identifier I of such an item. The expected result is:
error(z1,2).
player(1,"Chelsea").
age(1,24).
player(2,"Bayern").
team("Chelsea").
age(2,25).
player(2,"Bayern").
team("Chelsea").
age(2,25).
player(3,"Chelsea").
age(3,18).
team("Chelsea").
team("Bayern").
seniorEnglish(X) :- player(X,Y), team(Y), age(X,A), Y="Chelsea", A>20.
@output("seniorEnglish").
It selects the senior English players. They are those who play with Chelsea with age greater than 20. The expected result is:
seniorEnglish(1).