factor/library/collections/sequences.factor

78 lines
2.0 KiB
Factor
Raw Normal View History

2005-04-02 02:39:33 -05:00
! Copyright (C) 2005 Slava Pestov.
2005-12-31 20:51:58 -05:00
! See http://factorcode.org/license.txt for BSD license.
2006-10-31 00:52:02 -05:00
IN: vectors
USING: arrays kernel sequences-internals ;
: <vector> ( n -- vector )
f <array> array>vector 0 over set-fill ;
2005-04-02 02:39:33 -05:00
IN: sequences
2006-10-31 00:52:02 -05:00
USING: errors generic math math-internals strings ;
2005-04-02 02:39:33 -05:00
2006-08-16 21:55:53 -04:00
GENERIC: length ( seq -- n )
GENERIC: set-length ( n seq -- )
GENERIC: nth ( n seq -- elt )
GENERIC: set-nth ( elt n seq -- )
GENERIC: thaw ( seq -- resizable-seq )
GENERIC: like ( seq prototype -- newseq )
2006-05-02 06:05:58 -04:00
: empty? ( seq -- ? ) length zero? ; inline
2005-07-16 23:01:51 -04:00
2006-08-09 16:14:54 -04:00
: delete-all ( seq -- ) 0 swap set-length ;
2006-08-16 21:55:53 -04:00
: first ( seq -- first ) 0 swap nth ; inline
: second ( seq -- second ) 1 swap nth ; inline
: third ( seq -- third ) 2 swap nth ; inline
: fourth ( seq -- fourth ) 3 swap nth ; inline
2006-08-16 21:55:53 -04:00
: push ( elt seq -- ) dup length swap set-nth ;
2005-07-16 22:16:18 -04:00
2005-09-23 01:22:04 -04:00
: ?push ( elt seq/f -- seq )
[ 1 <vector> ] unless* [ push ] keep ;
2005-10-01 01:44:49 -04:00
: bounds-check? ( n seq -- ? )
over 0 >= [ length < ] [ 2drop f ] if ; inline
2005-10-01 01:44:49 -04:00
IN: sequences-internals
2006-08-16 21:55:53 -04:00
GENERIC: resize ( n seq -- newseq )
2005-12-31 20:51:58 -05:00
! Unsafe sequence protocol for inner loops
2006-08-16 21:55:53 -04:00
GENERIC: nth-unsafe ( n seq -- elt )
GENERIC: set-nth-unsafe ( elt n seq -- )
M: object nth-unsafe nth ;
M: object set-nth-unsafe set-nth ;
: 2nth-unsafe ( s s n -- x x )
tuck swap nth-unsafe >r swap nth-unsafe r> ; inline
2006-05-17 14:55:46 -04:00
! The f object supports the sequence protocol trivially
M: f length drop 0 ;
M: f nth nip ;
M: f nth-unsafe nip ;
2006-05-17 19:44:30 -04:00
M: f like drop dup empty? [ drop f ] when ;
2006-05-17 14:55:46 -04:00
2005-09-24 16:34:10 -04:00
! Integers support the sequence protocol
M: integer length ;
M: integer nth drop ;
M: integer nth-unsafe drop ;
2006-08-16 21:55:53 -04:00
: first2-unsafe
[ 0 swap nth-unsafe ] keep 1 swap nth-unsafe ; inline
: first3-unsafe
[ first2-unsafe ] keep 2 swap nth-unsafe ; inline
: first4-unsafe
[ first3-unsafe ] keep 3 swap nth-unsafe ; inline
2006-03-14 16:51:09 -05:00
2006-08-17 23:08:04 -04:00
: exchange-unsafe ( m n seq -- )
2006-03-14 16:51:09 -05:00
[ tuck nth-unsafe >r nth-unsafe r> ] 3keep tuck
>r >r set-nth-unsafe r> r> set-nth-unsafe ; inline
2006-07-28 03:54:46 -04:00
IN: sequences
: ?nth ( n seq/f -- elt/f )
2dup bounds-check? [ nth-unsafe ] [ 2drop f ] if ;