rules(&t(X,Y)) := needs(&t(X,Y)), &r(X, sym(Y)).
rules(&t(X,Y,Z)) := needs(&t(X,Y,Z)), needs(Z), &r(X, sym(Y), sym(Z)).
+% count the number of words in a subtree
+numwords(X) := 1.
+numwords(t(X,Y)) := numwords(Y).
+numwords(t(X,Y,Z)) := numwords(Y) + numwords(Z).
+
+% extract word and it's position in tree
+word(0, X) := X.
+word(I, t(X,Y)) := word(I, Y).
+word(I, t(X,Y,Z)) := I < numwords(Y), word(I, Y).
+word(I, t(X,Y,Z)) := I >= numwords(Y), word(I-numwords(Y), Z).
+
% unnormalized
c(X,Y) += r(X,Y) is rules(&t(X1,Y1)), 1.
c(X,Y,Z) += r(X,Y,Z) is rules(&t(X1,Y1,Z1)), 1.