factor/library/collections/sequences.factor

64 lines
1.8 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.
2005-04-02 02:39:33 -05:00
IN: sequences
2005-05-05 22:30:58 -04:00
USING: errors generic kernel math math-internals strings vectors ;
2005-04-02 02:39:33 -05:00
GENERIC: length ( sequence -- n ) flushable
GENERIC: set-length ( n sequence -- )
GENERIC: nth ( n sequence -- obj ) flushable
GENERIC: set-nth ( value n sequence -- obj )
GENERIC: thaw ( seq -- mutable-seq ) flushable
GENERIC: like ( seq seq -- seq ) flushable
GENERIC: reverse ( seq -- seq ) flushable
GENERIC: reverse-slice ( seq -- seq ) flushable
2006-05-02 06:05:58 -04:00
: empty? ( seq -- ? ) length zero? ; inline
2005-07-16 23:01:51 -04:00
: first 0 swap nth ; inline
: second 1 swap nth ; inline
: third 2 swap nth ; inline
: fourth 3 swap nth ; inline
2005-07-16 22:16:18 -04:00
: push ( element sequence -- )
2006-05-02 06:05:58 -04:00
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 ;
2005-10-14 04:05:02 -04:00
: ?nth ( n seq/f -- elt/f )
2006-01-02 00:51:03 -05:00
2dup bounds-check? [ nth ] [ 2drop f ] if ;
2005-10-14 04:05:02 -04:00
IN: sequences-internals
2005-12-31 20:51:58 -05:00
GENERIC: resize ( n seq -- seq )
! Unsafe sequence protocol for inner loops
GENERIC: nth-unsafe
GENERIC: set-nth-unsafe
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
: change-nth-unsafe ( seq i quot -- )
pick pick >r >r >r swap nth-unsafe
r> call r> r> swap set-nth-unsafe ; inline
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 ;
: 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
: exchange-unsafe ( n n seq -- )
[ tuck nth-unsafe >r nth-unsafe r> ] 3keep tuck
>r >r set-nth-unsafe r> r> set-nth-unsafe ; inline