Lecture 19 Part 3: More Visitors

Ambient temperature: 74.5oF

Concepts

  1. There are three approaches to the “sum” algorithm on the NEList/MTList list structure:
    1. nonEmptyCase(…) { return MY_VALUE + rest_of_list.execute( this ); }
      This is TAIL recursion, and accumulates the return value on the STACK. Another name for it is “Forward Accumulation.”
    2. nonEmptyCase(…) { return rest_of_list.execute( this ) + MY_VALUE; }
      This is HEAD recursion (and therefore bad), and accumulates the return value on the STACK. Don’t do this. Another name for this is “Reverse Accumulation.”
    3. nonEmptyCase(…) { return rest_of_list.execute( new SumVisitor( MY_VALUE + VALUE ) ); }
      This is TAIL recursion, and accumulates the return value in an INSTANCE VARIABLE inside the SumVisitor. This version allows your visitors to have, preserve, pass, and mutate STATE, which allows for more complex algorithms.
  2. Most of the list algorithms traverse the list; therefore list traversal is an INVARIANT behavior and should be abstracted out. Instead, “what to do with each subsequent value” is encoded in an Accumulator object, which is passed down the list by the visitor.

Resources

  1. Lecture 19 webpage: http://www.clear.rice.edu/comp310/f12/lectures/lec19/