/* Demonstration program to test classes representing elements of D Written 9/16/2002 by Kim Bruce */ public class ListTry { /* Reverse program from page 30, example 2.1.4, of Jones. Note the changes that had to be made. "nil" is now "D.nil", "while X do" is now "while (X != D.dFalse) {", and all operations are written in o-o form. Thus cons(x,y) is now y.cons(x) */ public static D reverse(D X) { D Y = D.nil; while (X != D.dFalse) { Y = Y.cons(X.hd()); X = X.tl(); } return Y; } /* Print some elements of D. Notice that you must generate atoms using the Atom constructor, and cons items using the Composite constructor. "nil" is obtained by writing "D.nil", while the constants for true and false are "D.dTrue" and "D.dFalse". The usual toString function on elements prints them using "." notation. You can check if an element in D can be represented as a list using X.isList(). If X does hold a value that can be represented as a list then X.asList() returns a string holding the list representation. Thus if X = (a.(b.(c.nil))) then X.asList() returns "( a, b, c )". If X does not hold a value that can be represented as a list then X.asList() returns a string with an error message. */ public static void main(String[] args) { D l1 = new Composite(new Atom("a"),D.nil); D l2 = new Composite(new Atom("b"),l1); D l3 = new Composite(new Atom("c"),l2); D l4 = new Composite(new Atom("b"), new Composite(new Atom("a"),new Atom("z"))); D X = new Composite(l3,l4); System.out.println("l1 = "+l1); System.out.println("l2 = "+l2); System.out.println("l3 = "+l3); System.out.println("l3 in list notation = "+l3.asList()); System.out.println("l4 = "+l4); System.out.println("l3.tl().eq(l4)"+" results in "+l3.tl().eq(l4)); System.out.println("l1.eq(l1)"+" results in "+l1.eq(l1)); System.out.println("l1.eq(l2)"+" results in "+l1.eq(l2)); D Y = reverse( l3 ); System.out.println("reverse l3 = "+Y); System.out.println("reverse l3 as list: "+Y.asList()); System.out.println("l4 is not a list, so l4 as list = "+l4.asList()); } }