]> gitweb.factorcode.org Git - factor.git/blob - extra/sequences/seq/seq.factor
sequences: Move some words to sequences.seq in extra.
[factor.git] / extra / sequences / seq / seq.factor
1 ! Copyright (C) 2022 Doug Coleman.
2 ! See http://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-loop ( dst dst-i src src-i src-stop -- dst )
22     2dup >= [
23         4drop
24     ] [
25         [
26             [ copy-nth-of-unsafe ] 4keep
27             [ 1 + ] 2dip 1 +
28         ] dip seq-copy-loop
29     ] if ; inline recursive
30
31 : seq-copy-unsafe ( dst dst-i src -- dst )
32     0 over length check-length seq-copy-loop ; inline
33
34 : seq-push-all ( dst src -- dst ) [ length seq-grow-copy ] keep seq-copy-unsafe ; inline
35
36 : seq-copy ( dst dst-n src -- dst ) check-grow-copy seq-copy-unsafe ; inline
37
38 <PRIVATE
39
40 : (seq-append) ( accum seq1 seq2 -- accum )
41     [
42         [ 0 ] dip [ seq-copy-unsafe ] [ length ] bi
43     ] dip seq-copy-unsafe ; inline
44
45 PRIVATE>
46
47 : seq-append-as ( seq1 seq2 exemplar -- newseq )
48     [ 2dup 2length + ] dip
49     [ -rot (seq-append) ] new-like ; inline
50
51 GENERIC: seq-bounds-check? ( seq n -- ? )
52
53 M: integer seq-bounds-check?
54     tuck lengthd > [ 0 >= ] [ drop f ] if ; inline
55
56 : seq-bounds-check ( seq n -- seq n )
57     2dup seq-bounds-check? [ swap bounds-error ] unless ; inline
58