Assignments
Rules can be enriched with assignments in order to generate specific values for existentially quantified variables of the head. Syntactically, the assignments follow the body of the rule. An assignment is the equation (=) of a variable (the LHS of the equation) of the body and an expression (the RHS of the equation).
Observe that although assignments and equality conditions are denoted by the same symbol (=), assignments and conditions can be unambiguously distinguished, since the LHS of the equation appears only in the head.
Each rule can have multiple comma-separated assignments.
balanceItem("loans",23.0).
balanceItem("deposits",20.0).
operations(Q,Z,A) :- balanceItem(I1,X),balanceItem(I2,Y), I1="loans",I2="deposits",Z=X+Y,A=(X+Y)/2.
@output("operations").
Example 20 generates a fact for operations, summing two balance items, one for loans and one for
deposits. Observe that I1="loans"
and I2="deposits"
are conditions to select
the balanceItems (as I1 and I2 appear in the body), whereas Z=X+Y
and A=(X+Y)/2
are assignments (as Z and A do not appear in the body).
The expected result is:
operations(z1,43,21.5).
projects("Mark",1,{1,5,7}).
projects("Mark",2,{4,5,6}).
all(X,P) :- projects(X,D1,P1), projects(X,D2,P2), D1>D2, P=P1|P2.
@output("all").
Example 21 calculates all the projects in which an employee is involved. D1>D2 guarantees that we are considering projects led in different departments. P is then calculated in an assignment as the union of the projects in department D1 and in department D2.
The expected result is:
all("Mark",{1, 4, 5, 6, 7}).