Previous page Table of Contents Next page
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) ; returns initial state end?(x is sequence, state is something) is boolean ; true if state is at end next(x is sequence, state is something) ; result is next element advance(x is sequence, state is something) ; result is 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 is something)
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 is next key (x is keyed-sequence)[key is something] ; result is element for key (x is keyed-sequence)[key is something, key: default] ; result is element or default
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. [] signals a run-time error if the key is invalid for the keyed-sequence, unless a default: is specified.
defprotocol assignable-keyed-sequence is keyed-sequence (x is keyed-sequence)[key is something] := new-element is something
The sequence function is a pseudo-constructor which returns a sequence. With no arguments, it returns an empty sequence. With one or more arguments, it returns an infinite sequence whose elements are the given arguments repeated over and over in the given order.
Previous page Table of Contents Next page