### Problem 1 (15 pts.)

Rectify the following rules.
``` p(X,Y,Z) :- q(X,X,Y,V) & q(Z,V,Y,a) q(X,Y,Z,W) :- p(X,Y,Y) & p(Y,Z,W) ```
```q(X,Y,Z,W) :- r(X,Y,Z,W,X) ```
Note that r is an EDB predicate and a is a constant.

### Problem 2 (15 pts.)

Suppose we have the relation R whose value is the four tuples (R1 and R2 are the first and second arguments of the relation R):
R1 R2
a b
f(a) g(b)
f(g(a)) g(f(b))
f(f(a)) f(a)

Perform the following translations

a)
Q(X,Y) = `ATOV`(p(f(X),g(Y)), R).

b)
Q(X,Y) = `ATOV`(p(f(X),X), R).

c)
Q(X,Y) = `VTOA`(p(h(X,Y),g(X)), R(X,Y)).

### Problem 3 (15 pts.)

Consider the rules
``` p(X,Y,Z) :- q(X,Y,Z) ```
``` p(X,Y,Z) :- q(X,S,Y) & p(Y,T,Z) ```
Draw the rule/goal graph starting with the goal for predicate p with adornment bff.

### Problem 4 (15 pts.)

For the rules in Problem 2 and query p(0,A,B), write the magic-set rules.

### Problem 5 (20 pts.)

Below are the rules that define terms representing the structure of arithmetic expressions with +,*, and parentheses.
``` expression(plus(E,T)) :- expression(E) & product(T). expression(E) :- product(E). product(times(T,F)) :- product(T) & factor(F). product(T) :- factor(T). factor(parens(E)) :- expression(E). ```
``` factor(F) :- identifier(F). ```
Write the magic-set rules for the query form expression with adornment b. For Group V you can imagine that the query is about some term e, which we are testing to see if it is a valid expression.

### Problem 6 (20 pts)

Suppose a REFER application wants to support the following global concepts:
1. doctor(D) = ``D is a doctor.''
2. nurse(N) = ``N is a nurse.''
3. patient(P) = ``P is a patient.''
4. diag(P,C) = ``patient P is diagnosed with condition C.''
5. operation(D,N,P) = ``an operation is performed by doctor D and nurse N on patient P.''
Let the query be:
``` ```
``` ans(N) :- operation(D,N,P) & doctor(D) & nurse(N) & patient(P) & diag(P,appendicitis) ```
That is, find the nurses who participated in appendectomies.

Suppose we want to run this query against a database with the following relations:

1. staff(Name, Position) gives the name (assumed unique) of staff (doctors and nurses) and their position (either "doctor" or "nurse").
2. patients(Name, Address, Condition) gives the name (again assumed unique), address, and condition (e.g., "appendicitis") of the patient.
3. assigned(S, P) meaning that staff member S is assigned to the operation on patient P.
a)
Write ``view definitions'' for each of the global concepts in terms of the relations at the source.

b)
Rewrite the query in terms of the source relations. Do not forget to use each subgoal of the query, even if it results in duplicate subgoals in the rewritten query.

c)
Optimize your query from (b) to remove redundant subgoals.