package listFW.visitor;

import listFW.*;



/**

 * Computes a String reprsentation of IList showing  a left parenthesis followed

 * by elements of the IList separated by commas, ending with with a right parenthesis.

 * This code has been written to make it run on any list.

 * @stereotype visitor

 * @author D.X. Nguyen, S. Wong

 * @since 07/01/2004

 */

public class ToStringAlgo implements IListAlgo<Object, String, Object> {

    

    public static final ToStringAlgo Singleton = new ToStringAlgo();

    private ToStringAlgo() {

    }

    

    /**

     * Returns "()".

     */

    public String emptyCase(IMTList<? extends Object> host, Object ... inp) {

        return "()";

    }

    

    /**

     * Passes "(" + first to the rest of IList and asks for help to complete the computation.

     */

    public String nonEmptyCase(INEList<? extends Object> host, Object ... inp) {

        return host.getRest().execute(ToStringHelper.Singleton, "(" + host.getFirst());

    }

}



/**

 * Helps ToStringAlgo compute the String representation of the rest of the list.

 */

class ToStringHelper implements IListAlgo<Object, String, String> {

    public static final ToStringHelper Singleton = new ToStringHelper();

    private ToStringHelper() {

    }

    

    /**

     * Returns the accumulated String + ")".

     * At end of list: done!  

     */

    public String emptyCase(IMTList<? extends Object> host, String ... acc) {

        return  acc[0] + ")";

    }

    

    /**

     * Continues accumulating the String representation by appending ", " + first to acc

     * and recur!

     */

    public String nonEmptyCase(INEList<? extends Object> host, String ... acc) {

        return host.getRest().execute(this, acc[0] + ", " + host.getFirst());

    }

}



