16.1.2 Basic collection methods
The |
|---|
define method size (sorted-sequence :: <sorted-sequence>)
=> (sorted-sequence-size :: <integer>)
sorted-sequence.data.size;
end method size;
define method shallow-copy (sorted-sequence :: <sorted-sequence>)
=> (copy :: <sorted-sequence>)
let copy
= make(<sorted-sequence>,
value-function: sorted-sequence.value-function,
comparison-function: sorted-sequence.comparison-function);
// The map-into function replaces the elements of the copy's data array
// to be the identical elements of the data array of sorted sequence
copy.data.size := sorted-sequence.data.size;
map-into(copy.data, identity, sorted-sequence.data);
copy;
end method shallow-copy;
define constant $unsupplied = list(#f);
define method element
(sorted-sequence :: <sorted-sequence>, key :: <integer>,
#key default = $unsupplied)
=> (element :: <object>);
if (key < sorted-sequence.data.size)
sorted-sequence.data[key];
elseif (default = $unsupplied)
error("Attempt to access key %= which is outside of %=.", key,
sorted-sequence);
else default;
end if;
end method element; |
In the preceding code, we define methods for determining the number of elements in the sorted sequence, for copying the sorted sequence (but not the elements stored in the sorted sequence), and for accessing a particular item in the sorted sequence. Once we have defined the element method for sorted sequences, we can use the subscripting syntax to access particular items in the sorted sequence. Our element method implements the standard Dylan protocol, which allows the caller to specify a default value if the key is not contained within the collection. If the key is not part of the collection, and no default value is specified, then an error is signaled. Since we do not export $unsupplied from our library, we can be certain that no one can supply that value as the default keyword parameter for our element method.
Note that the element-setter method is not defined, because it does not make sense to store an element at a particular position within the sorted sequence. The sorted sequence itself determines the correct key for each item added to the sorted sequence, based on the item being added and on the value and comparison functions.
Next, we show methods for adding and removing elements from sorted sequences.




