Sequence protocol
Factor handbook » The language » Collections » Sequence operations

Next:The f object as a sequence


All sequences must be instances of a mixin class:
Image
sequence

Image
sequence? ( object -- ? )


All sequences must know their length:
Image
length ( seq -- n )


At least one of the following two generic words must have a method for accessing elements; the sequence mixin has default definitions which are mutually recursive:
Image
nth ( n seq -- elt )

Image
nth-unsafe ( n seq -- elt )

Image
?nth ( n seq -- elt/f )


Note that sequences are always indexed starting from zero.

At least one of the following two generic words must have a method for storing elements; the sequence mixin has default definitions which are mutually recursive:
Image
set-nth ( elt n seq -- )

Image
set-nth-unsafe ( elt n seq -- )

Image
?set-nth ( elt n seq -- )


If your sequence is immutable, then you must implement either set-nth or set-nth-unsafe to simply call immutable to signal an error.

The following two generic words are optional, as not all sequences are resizable:
Image
set-length ( n seq -- )

Image
lengthen ( n seq -- )


An optional generic word for creating sequences of the same class as a given sequence:
Image
like ( seq exemplar -- newseq )


Optional generic words for optimization purposes:
Image
new-sequence ( len seq -- newseq )

Image
new-resizable ( len seq -- newseq )


See also
Unsafe sequence operations