package schemeFactory.visitor; import schemeFactory.*; /** * Reverses the host list by accumulating the reverse as one traverses the list. * This is best done via a helper visitor. The accumulated reverse list can be * viewed as a "stack": just stack the first as one traverses down the list; by * the time the end is reached, the accumulated stack is the reverse list. The * end of a list is marked by the empty list. * @author D. X. Nguyen */ public class Reverse implements IListAlgo { private IListFactory _fact; public Reverse(IListFactory f) { _fact = f; } /** * Returns the host since the reverse of the empty list is the empty list. * @param host * @param input not used * @return AList */ public Object emptyCase(AList host, Object input) { return host; } /** * Passes to the host's rest the list consisting of the host's first as the * accumulated reverse of the list preceding the host's rest, and asks for * help to reverse the host. * @param host * @param input not used * @return AList */ public Object nonEmptyCase(AList host, Object input) { AList accReverse = _fact.makeNEList(host.getFirst(), _fact.makeEmptyList()); return host.getRest().execute(new IListAlgo() { /** * Returns the accumulated reverse because this is the end of the list. * @param h not used * @param acc the accumulated reverse of the list preceding h. * @return AList */ public Object emptyCase(AList h, Object acc) { return acc; } /** * Accumulates the reverse by cons-ing h's first with the * accumulated reverse so far, and recur on the h's rest. * @param h the rest of the list to be reversed. * @param acc the accumulated reverse of the list preceding h. * @return AList */ public Object nonEmptyCase(AList h, Object acc) { AList stack = _fact.makeNEList(h.getFirst(), (AList)acc); return h.getRest().execute (this, stack); } }, accReverse); } }