Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
abstract class IntList {
    abstract int sum(); // all IntLists know how to sum themselves!
}

class EmptyIntList extends IntList {
    static EmptyIntList ONLY = new EmptyIntList(); // Singleton
    private EmptyIntList() {}
 
   /**
    * The sum of an empty list
    * @return zero always
    */
    int sum() {
        return 0; // base case code
    }
}

class ConsIntList extends IntList {
    int first;
    IntList rest;

   /**
    * The sum of a non-empty list
    * @return first plus the sum of rest
    */
    int sum() {
        return first + rest.sum()  ; // inductive case code
    }
}

...