// file: list1.java // author: Robert Keller // purpose: expansion of the List class, open list of integers // In the open list concept, a List is a REFERENCE to the first cell // of the list. // Thus the empty List is identified with null, the null reference, // which is part of the Java language. // // cons(F, R) creates a List from an element F and a list R. // first(L) returns the first of a non-empty list // rest(L) returns all but the first of a non-empty list // isEmpty(L) tells whether L is empty // print(L, S) prints L in PrintStream S import java.io.PrintStream; class List { int First; // every non-empty list has List Rest; // these two things static List cons(int First, List Rest) // creat a new list { return new List(First, Rest); // defined in constructor below } static int first(List L) // get First { return L.First; } static List rest(List L) // get Rest { return L.Rest; } static boolean isEmpty(List L) // tell whether empty { return L == null; } static final List nil = null; // empty list static void print(List L, PrintStream S) // print list as (1 2 3 ....) { S.print("("); // print opening "(" if( !isEmpty(L) ) { S.print(first(L)); // print first element if any L = rest(L); while( !isEmpty(L) ) // print rest of elements { S.print(" "); S.print(first(L)); L = rest(L); } } S.print(")"); // print closing ")" } public static void main(String arg[]) // main program or test { List L = cons(1, cons(2, cons(3, cons(4, null)))); System.out.print("L = "); print(L, System.out); System.out.println(); } List(int First, List Rest) // List constructor { this.First = First; this.Rest = Rest; } }