Little Java Exerices 1
Practice the Composite and Interpreter Patterns

Before doing these exercises, you should read the classnotes. through Section 1.7.

Classes

The file ~comp212/hw/01/IntList.java contains the definition of a "functional" formulation of lists of int elements. This class definition supports five important operations: Note that the methods getFirst() and getRest() generate run-time errors (by throwing run-time exceptions) if they are applied Empty objects.

Similarly, the file ~comp212/hw/01/Tree.java contains the definition of a Tree class. Each object of type Tree represents either a leaf containing an int or a branch containing two subtrees. The class definition for Tree supports three important operations:

Problems

Copy the files ~comp212/hw/01/{IntList,Tree}.java into a new folder and modify them as follows.
  1. Add the method int sum() to class IntList. Calling s.sum() returns the sum of all the numbers in s.
  2. Add the method int sum() to the class Tree.
  3. Add the methods int size() to the class Tree. For example, the Tree
               /\
              /\ 13
             7 /\ 
              9  11
    
    has size is seven: four leaves, three branches. (It requires seven new statements to build this Tree.)

    A small amount of extra credit: How can you build a tree with this same shape (but possibly different numbers) using four new statements? Fewer? Note that the size of any such trees is still seven.

  4. Going back to the file IntList.java, write the method int max(), which returns the maximum element of a Cons object only. On Emptys, max() should return an IllegalArgumentException.
  5. Write the Cons method dup(), which returns a new list with the first element duplicated.1 That is, if l1 were the list (4, 5, 6), then l1.dup() would be the list (4, 4, 5, 6). In your test cases, include a test of dup on a variable which is declared to be of class IntList. (You will need to do a cast.) Does your function max() still work fine on lists returned by dup()?
For each of the above problems, be sure to add test cases which cover all reasonable cases. For instance, the method IntList.sum() should be tested on lists of length zero, one, and more-than-one.

Good coding style is important. Good style includes reasonable variable names, a purpose statement in a comment before each non-overridden function, and reasonable indentation2) All programs in this exercise should be written in a purely functional style: no object fields should be modified once they have been initialized by a constructor.


1 The name dup derives from stack-bases calculators and languages like Postscript, where it duplicates the top element of the stack. (back)

2 Remember that DrJava can indent entire programs. Select the entire program with the mouse and hit the TAB key. (back)


cork@rice.edu           Please let me know of any broken links             Revised 02.Aug.8