001    package listFW.visitor;
002    
003    import fp.*;
004    import listFW.*;
005    
006    /**
007     * Folds a list, starting at the right side.
008     * @param b[0] is the initial value.
009     */
010    public class FoldR<T,P> implements IListAlgo<T,P,P> {
011      private ILambda2<P,T,P> _f;
012      /**
013       * Constructor for a FoldR algorithm.
014       * @param f a binary ILambda, i.e. one that takes two parameters as varargs.
015       */
016      public FoldR(ILambda2<P,T,P> f) {
017        _f = f;
018      }
019    
020      /**
021       * Empty case. Return the initial value.
022       * @param b b[0] is the initial value.
023       * @return initial value
024       */
025      public P emptyCase(IMTList<? extends T> h, P... b) {
026        return b[0];
027      }
028      
029      /**
030       * Non-empty case. Apply lambda to initial value and first, and recur.
031       * @param b b[0] is the initial value.
032       * @return result of folding
033       */
034      public P nonEmptyCase(INEList<? extends T> h, P... b) {
035        return _f.apply(h.getFirst(), h.getRest().execute(this, b));
036      }
037      
038    }