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-unsafe ( dst dst-i src -- dst )
22 0 over length check-length copy-loop ; inline
24 : seq-push-all ( dst src -- dst ) [ length seq-grow-copy ] keep seq-copy-unsafe ; inline
26 : seq-copy ( dst dst-n src -- dst ) check-grow-copy seq-copy-unsafe ; inline
30 : (seq-append) ( accum seq1 seq2 -- accum )
32 [ 0 ] dip [ seq-copy-unsafe ] [ length ] bi
33 ] dip seq-copy-unsafe ; inline
37 : seq-append-as ( seq1 seq2 exemplar -- newseq )
38 [ 2dup 2length + ] dip
39 [ -rot (seq-append) ] new-like ; inline
41 GENERIC: seq-bounds-check? ( seq n -- ? )
43 M: integer seq-bounds-check?
44 tuck lengthd > [ 0 >= ] [ drop f ] if ; inline
46 : seq-bounds-check ( seq n -- seq n )
47 2dup seq-bounds-check? [ swap bounds-error ] unless ; inline