Module hw06

Class SumFwdAlgo

java.lang.Object
provided.listFW.visitors.SumFwdAlgo
All Implemented Interfaces:
IListAlgo

public class SumFwdAlgo extends Object implements IListAlgo
Returns the sum of a list of integers using forward accumulation. The input parameter is not used ("nu").
Author:
swong
  • Field Details

    • helper

      private IListAlgo helper
      Recursive helper that uses an accumulator as its input parameter.
  • Constructor Details

    • SumFwdAlgo

      public SumFwdAlgo()
  • Method Details

    • emptyCase

      public Object emptyCase(MTList host, Object... nu)
      Description copied from interface: IListAlgo
      Operates on MTList, the empty list. Since IEmptyList has only one method, execute(), there is not much the host list can do here. So the code for the empty case usually involves:
      • inp, and perhaps
      • host.execute(..., ...).
      Specified by:
      emptyCase in interface IListAlgo
      Parameters:
      host - the MTList that is executing this algorithm.
      nu - a variable number of input parameters that can be used for any purpose.
      Returns:
      result from calling this method. The type of the result is problem-specific and may be null.
    • nonEmptyCase

      public Object nonEmptyCase(NEList host, Object... nu)
      Description copied from interface: IListAlgo
      Operates on NEList, a non-empty list. The host list now has a first and a rest. So the code here usually involves what host.getFirst() and host.getRest() can do to accomplish the task at hand.
      • host.getFirst() is simply a data Object that the host list holds. It is problem-specific, and thus what it can do depends on the problem the current algorithm is trying to solve.
      • host.getRest() in contrast is an IList! What can an IList do? execute an alogrithm IListAlgo with some input. What IListAlgo can that be? The current algorithm that is being executed is as good a candidate as any other IListAlgo. In Java, we use the key word this to reference the current receiver of the method call. Having the rest of host (recursively) execute the current algorithm is expressed in Java as: host.getRest().execute(this, ...).

      To summarize, the code for the non-empty case usually involves:

      • host.getFirst(), and the recursive call
      • host.getRest().execute(this, something involving inp).
      Specified by:
      nonEmptyCase in interface IListAlgo
      Parameters:
      host - the NEList that is executing this algorithm
      nu - a variable number of input parameters that can be used for any purpose.
      Returns:
      result from calling this method. The type of the result is problem-specific and may be null.