1 ! Copyright (C) 2022 Doug Coleman.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: kernel math sequences sequences.private ;
6 ! Experimental: possibly more natural implementation of some sequence words.
8 GENERIC#: seq-lengthen 1 ( seq n -- seq )
9 GENERIC#: seq-shorten 1 ( seq n -- seq )
11 : seq-set-length ( seq n -- seq ) [ swap set-length ] keepd ; inline
13 M: sequence seq-lengthen 2dup lengthd < [ seq-set-length ] [ drop ] if ; inline
14 M: sequence seq-shorten 2dup lengthd > [ seq-set-length ] [ drop ] if ; inline
16 : seq-push ( seq elt -- seq ) [ dup length ] dip set-nth-of ;
18 : seq-grow-copy ( dst n -- dst dst-n )
19 [ over length + seq-lengthen ] keep 1 - ; inline
21 : seq-copy-loop ( dst dst-i src src-i src-stop -- dst )
26 [ copy-nth-of-unsafe ] 4keep
29 ] if ; inline recursive
31 : seq-copy-unsafe ( dst dst-i src -- dst )
32 0 over length check-length seq-copy-loop ; inline
34 : seq-push-all ( dst src -- dst ) [ length seq-grow-copy ] keep seq-copy-unsafe ; inline
36 : seq-copy ( dst dst-n src -- dst ) check-grow-copy seq-copy-unsafe ; inline
40 : (seq-append) ( accum seq1 seq2 -- accum )
42 [ 0 ] dip [ seq-copy-unsafe ] [ length ] bi
43 ] dip seq-copy-unsafe ; inline
47 : seq-append-as ( seq1 seq2 exemplar -- newseq )
48 [ 2dup 2length + ] dip
49 [ -rot (seq-append) ] new-like ; inline
51 GENERIC: seq-bounds-check? ( seq n -- ? )
53 M: integer seq-bounds-check?
54 tuck lengthd > [ 0 >= ] [ drop f ] if ; inline
56 : seq-bounds-check ( seq n -- seq n )
57 2dup seq-bounds-check? [ swap bounds-error ] unless ; inline