package lrs.visitor;
import lrs.*;
/**
* Replaces each pair of consecutive Integers in the host with their sum.
* For a host with an odd number of elements, the last element is left
* unchanged.
* Assumes host contains Integer.
* @author D. X. Nguyen
* @author S. B. Wong
* @since 10/09/01
*/
public class AddPairs implements IAlgo {
public static final AddPairs Singleton = new AddPairs();
private AddPairs() {
}
public Object emptyCase(LRStruct host, Object inp) {
return null;
}
/**
* Removes the host's front: host is now its previous rest;
* Inserts the old front back to the (new) host if it si empty, else
* sets the host's first to the sum of the old front and the current first,
* and recurs on the host's rest.
*/
public Object nonEmptyCase(LRStruct host, Object inp) {
return host.execute(new IAlgo() {
/**
* Puts back the (outer) host's first since there is no more
* data.
* @param h the rest of the (outer) host.
* @param i Integer the (outer) host's first.
* @return null
*/
public Object emptyCase(LRStruct h, Object i) {
h.insertFront(i);
return null;
}
/**
* Sets the host's first to the sum of its first and the input;
* Recurs on the outer visitor, AddPairs.
* @param h the rest of the (outer) host.
* @param i Integer the (outer) host's first.
* @return null
*/
public Object nonEmptyCase(LRStruct h, Object i) {
int iVal = ((Integer)i).intValue();
int fVal = ((Integer)h.getFirst()).intValue();
h.setFirst(new Integer(iVal + fVal));
return h.getRest().execute(AddPairs.this, null);
// The above two lines of code can be chained together as:
// return h.setFirst(new Integer(iVal + fVal)).getRest().execute(AddPairs.this, null);
}
}
, host.removeFront()); // host is now its rest!
}
}