Average.java
Created with JBuilder
package lrs.visitor;

import lrs.IAlgo;
import lrs.LRStruct;

/**
 * Computes the average of an LRStruct of Doubles.  Mathematically, the average
 * of an empty list does not exist.  We return null in this case.  null is used
 * to represent non-existence.
 * @author D. X. Nguyen
 * @version 1.0
 */
public class Average implements IAlgo {

    private int _accLen = 0;       // accumulated length
    private double _accSum = 0.0;  // accumulated sum

    public Average() {
    }

    public Object emptyCase(LRStruct host, Object notUsed) {
        return null;
    }

    /**
     * Initializes the accumulated length and the accumluated sum, and asks the
     * rest to execute a helper algorithm to figure out the average.  The helper
     * algorithm is an anonymous (local) inner class that has access to the
     * private fields of the outer algorithm and can update them accordingly.
     */
    public Object nonEmptyCase(LRStruct host, Object notUsed) {
        _accLen = 1;
        _accSum = ((Double)host.getFirst()).doubleValue();
        return host.getRest().execute(new IAlgo() {
            /**
             * At this point, the accumulated length is the length of the host,
             * the accumulated sum is the sum of the host.  The average is thus
             * the ration of the accumulated sum over the accumulated length.
             */
            public Object emptyCase(LRStruct h, Object nu) {
                return new Double(_accSum / _accLen);
            }

            /**
             * Updates the accumulated length and accumulated sum in the outer
             * algorithm, and recurs on the rest of the host h.
             */
            public Object nonEmptyCase(LRStruct h, Object nu) {
                _accLen++;
                _accSum += ((Double)h.getFirst()).doubleValue();
                return h.getRest().execute(this, null);
            }
        }
        , null);
    }
}

Average.java
Created with JBuilder