Programming Language for Old Timers


by David A. Moon
February 2006 .. September 2008

Comments and criticisms to dave underscore moon atsign alum dot mit dot edu.


Previous page   Table of Contents   Next page


Sequence Iteration Protocol

Perhaps the most fundamental protocol is sequence. Any object that implements the sequence protocol possesses a series of elements that can be accessed one at a time through iteration. The order in which iteration visits the elements is meaningful for most sequences, but it is not required to be meaningful nor repeatable if multiple iterations are done over the same sequence.

Iteration uses a current state object whose type is completely dependent on the type of the sequence object.

The following method requirements constitute the sequence protocol:

defprotocol sequence
  start-iteration(x is sequence, result: state is anything)
  end?(x is sequence, state is something, result: end? is boolean)
  next(x is sequence, state is something, result: element)
  advance(x is sequence, state is something, result: new-state)

start-iteration returns the initial state.

end? checks whether a state is the ending state, i.e. advanced past all elements.

next returns the element associated with the current state. If the end has been reached, the result is undefined.

advance returns the next state. If called when the end has been reached, advance returns a valid state which is still at the end.

A subprotocol is assignable-sequence, which adds this method requirement:

defprotocol assignable-sequence is sequence
  next:=(x is sequence, state is something, new-element)

which replaces the element associated with the current state. If the end has been reached an error occurs. Like all assignment methods this method returns its last argument.

Another subprotocol is keyed-sequence, which adds these method requirements:

defprotocol keyed-sequence is sequence
  next-key(x is keyed-sequence, state is something, result: key)
  (x is keyed-sequence)[key is something], result: element

next-key returns a key associated with the current state. If the end has been reached, the result is undefined. This can be used with the [] macro to access the element associated with the current state.

defprotocol assignable-keyed-sequence is keyed-sequence
  (x is keyed-sequence)[key is something] := new-element


Previous page   Table of Contents   Next page