]> gitweb.factorcode.org Git - factor.git/blob - extra/sequences/seq/seq.factor
factor: update http to https for licenses
[factor.git] / extra / sequences / seq / seq.factor
1 ! Copyright (C) 2022 Doug Coleman.
2 ! See https://factorcode.org/license.txt for BSD license.
3 USING: kernel math sequences sequences.private ;
4 IN: sequences.seq
5
6 ! Experimental: possibly more natural implementation of some sequence words.
7
8 GENERIC#: seq-lengthen 1 ( seq n -- seq )
9 GENERIC#: seq-shorten 1 ( seq n -- seq )
10
11 : seq-set-length ( seq n -- seq ) [ swap set-length ] keepd ; inline
12
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
15
16 : seq-push ( seq elt -- seq ) [ dup length ] dip set-nth-of ;
17
18 : seq-grow-copy ( dst n -- dst dst-n )
19     [ over length + seq-lengthen ] keep 1 - ; inline
20
21 : seq-copy-unsafe ( dst dst-i src -- dst )
22     0 over length check-length copy-loop ; inline
23
24 : seq-push-all ( dst src -- dst ) [ length seq-grow-copy ] keep seq-copy-unsafe ; inline
25
26 : seq-copy ( dst dst-n src -- dst ) check-grow-copy seq-copy-unsafe ; inline
27
28 <PRIVATE
29
30 : (seq-append) ( accum seq1 seq2 -- accum )
31     [
32         [ 0 ] dip [ seq-copy-unsafe ] [ length ] bi
33     ] dip seq-copy-unsafe ; inline
34
35 PRIVATE>
36
37 : seq-append-as ( seq1 seq2 exemplar -- newseq )
38     [ 2dup 2length + ] dip
39     [ -rot (seq-append) ] new-like ; inline
40
41 GENERIC: seq-bounds-check? ( seq n -- ? )
42
43 M: integer seq-bounds-check?
44     tuck lengthd > [ 0 >= ] [ drop f ] if ; inline
45
46 : seq-bounds-check ( seq n -- seq n )
47     2dup seq-bounds-check? [ swap bounds-error ] unless ; inline
48