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 03/29/05 */ public class AddPairs implements IAlgo { public static final AddPairs Singleton = new AddPairs(); private AddPairs() { } public Object emptyCase(LRStruct host, Object... nu) { 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... nu) { 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 [0] Integer the (outer) host's first. * @return null */ public Object emptyCase(LRStruct h, Object... i) { h.insertFront(i[0]); 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 [0] Integer the (outer) host's first. * @return null */ public Object nonEmptyCase(LRStruct h, Object... i) { h.setFirst((Integer)i[0] + (Integer)h.getFirst()); return h.getRest().execute(AddPairs.this); } } , host.removeFront()); // host is now its rest! } }