

package lrs.visitor;

import counter.*;

import lrs.*;



/**

 * Returns the nth element in a LRS.

 */

public class Nth implements IAlgo {

  public static final Nth Singleton = new Nth();

  

  private Nth(){}

  

  public Object emptyCase(LRStruct host, Object... param)

  {

    return (null); // No such element exists

  }

  

  public Object nonEmptyCase(LRStruct host, Object... param)

  {

    return (((ICounter) param[0]).execute(counterAlgo, host)); //

  }

  

  private static final ICounterAlgo counterAlgo = new ICounterAlgo() {

    /**

     * @param host counter to be operated on

     * @param param LRS to be operated on

     * @return the first element.

     */

    public Object zeroCase(ICounter chost, Object... param) {

      // param is the host of the null/nonNull cases.

      return (((LRStruct)param[0]).getFirst ());

    }

    

    /**

     * @param host 

     * @param param 

     * @return 

     */

    public Object nonZeroCase(ICounter chost, Object... param) {

      return (((LRStruct) param[0]).getRest ().execute (Nth.Singleton, chost.decrement ()));

    }    

  };

}



