// file: NonEmptyList.java // author: Robert Keller // purpose: NonEmptyList class of Poly package package Poly; import java.io.*; import java.lang.*; /** * NonEmptyList is the sub-class of List consisting of non-empty * lists. Every NonEmptyList has a first and a rest. **/ public class NonEmptyList extends List { private Object First; private Object Rest; /** * isEmpty() tells whether the List is empty. **/ public boolean isEmpty() { return false; } /** * nonEmpty() tells whether the List is non-empty. **/ public boolean nonEmpty() { return true; } /** * first() returns the first element of a NonEmptyList. * @exception EmptyListException is never thrown. **/ public Object first() { return First; } /** * rest() returns the rest of a NonEmptyList. * @exception EmptyListException is never thrown. **/ public List rest() { if( Rest instanceof Seed ) { Rest = ((Seed)Rest).grow(); } return (List)Rest; } /** * NonEmptyList is the constructor for a List, given a First and a Rest. * * Use static method cons to avoid using 'new' explicitly. **/ public NonEmptyList(Object First, List Rest) { this.First = First; this.Rest = Rest; } public NonEmptyList(Object First, Seed Rest) { this.First = First; this.Rest = Rest; } /** * getNonEmpty() returns this list. * @exception EmptyListException is never thrown. **/ public NonEmptyList getNonEmpty() { return this; } /** * toString() converts List to string, e.g. for printing **/ public String toString() { try { StringBuffer buff = new StringBuffer(); buff.append("("); buff.append(first().toString()); List L = rest(); // print the rest of the items for( ; ; ) { if( L instanceof Incremental && !((Incremental)L).grown() ) { buff.append(" ..."); break; } if( L.isEmpty() ) break; NonEmptyList L2 = L.getNonEmpty(); buff.append(" "); buff.append(L2.first().toString()); L = L2.rest(); } buff.append(")"); return buff.toString(); } catch( EmptyListException e ) { System.err.println("*** Internal error, NonEmptyList expected"); return ""; } } /** * setFirst() sets the first element of a NonEmptyList. **/ public void setFirst(Object value) { First = value; } } // class NonEmptyList