001    
002    package lrs.visitor;
003    import counter.*;
004    import lrs.*;
005    
006    /**
007     * Returns the nth element in a LRS.
008     */
009    public class Nth implements IAlgo {
010      public static final Nth Singleton = new Nth();
011      
012      private Nth(){}
013      
014      public Object emptyCase(LRStruct host, Object... param)
015      {
016        return (null); // No such element exists
017      }
018      
019      public Object nonEmptyCase(LRStruct host, Object... param)
020      {
021        return (((ICounter) param[0]).execute(counterAlgo, host)); //
022      }
023      
024      private static final ICounterAlgo counterAlgo = new ICounterAlgo() {
025        /**
026         * @param host counter to be operated on
027         * @param param LRS to be operated on
028         * @return the first element.
029         */
030        public Object zeroCase(ICounter chost, Object... param) {
031          // param is the host of the null/nonNull cases.
032          return (((LRStruct)param[0]).getFirst ());
033        }
034        
035        /**
036         * @param host 
037         * @param param 
038         * @return 
039         */
040        public Object nonZeroCase(ICounter chost, Object... param) {
041          return (((LRStruct) param[0]).getRest ().execute (Nth.Singleton, chost.decrement ()));
042        }    
043      };
044    }
045