1 ! Copyright (C) 2005, 2010 Slava Pestov, Joe Groff.
2 ! See https://factorcode.org/license.txt for BSD license.
3 USING: accessors kernel math math.order sequences
7 ERROR: groups-error seq n ;
11 GENERIC: group@ ( n groups -- from to seq )
13 TUPLE: chunking { seq read-only } { n read-only } ;
15 INSTANCE: chunking sequence
17 M: chunking nth-unsafe group@ <slice-unsafe> ; inline
19 M: chunking set-nth-unsafe group@ <slice-unsafe> 0 swap copy ;
21 M: chunking like drop { } like ; inline
23 : check-groups ( seq n -- seq n )
24 dup 0 <= [ groups-error ] when ; inline
26 : new-groups ( seq n class -- groups )
27 [ check-groups ] dip boa ; inline
31 TUPLE: groups < chunking ;
34 [ seq>> length ] [ n>> ] bi [ + 1 - ] keep /i ; inline
37 [ n>> * ] [ seq>> ] bi set-length ; inline
40 [ n>> [ * dup ] keep + ] [ seq>> ] bi [ length min ] keep ; inline
42 : <groups> ( seq n -- groups )
43 groups new-groups ; inline
45 TUPLE: clumps < chunking ;
48 dup seq>> length [ drop 0 ] [
49 swap [ 1 + ] [ n>> ] bi* [-]
53 [ n>> + 1 - ] [ seq>> ] bi set-length ; inline
56 [ n>> over + ] [ seq>> ] bi ; inline
58 : <clumps> ( seq n -- clumps )
59 clumps new-groups ; inline
63 : map-like ( seq n quot -- seq )
64 keepd '[ _ like ] map ; inline
68 : group ( seq n -- array ) [ <groups> ] map-like ; inline
70 : clump ( seq n -- array ) [ <clumps> ] map-like ; inline
72 : monotonic? ( seq quot: ( elt1 elt2 -- ? ) -- ? )
73 over length dup 2 < [ 3drop t ] [
75 [ first2-unsafe ] dip call
79 [ >underlying< [ nth-unsafe ] curry [ 1 + ] 2dip ] bi
80 ] dip '[ @ _ keep swap ] all-integers-from? nip
84 : all-equal? ( seq -- ? ) [ = ] monotonic? ;
86 : all-eq? ( seq -- ? ) [ eq? ] monotonic? ;
89 { from integer read-only }
90 { to integer read-only }
93 INSTANCE: circular-slice virtual-sequence
95 M: circular-slice equal? over circular-slice? [ sequence= ] [ 2drop f ] if ;
97 M: circular-slice hashcode* [ sequence-hashcode ] recursive-hashcode ;
99 M: circular-slice length [ to>> ] [ from>> ] bi - ; inline
101 M: circular-slice virtual-exemplar seq>> ; inline
103 M: circular-slice virtual@
104 [ from>> + ] [ seq>> ] bi [ length rem ] keep ; inline
106 C: <circular-slice> circular-slice
108 TUPLE: circular-clumps
112 INSTANCE: circular-clumps sequence
114 M: circular-clumps length
115 seq>> length ; inline
117 M: circular-clumps nth
118 [ n>> over + ] [ seq>> ] bi <circular-slice> ; inline
120 : <circular-clumps> ( seq n -- clumps )
121 circular-clumps new-groups ; inline
123 : circular-clump ( seq n -- array )
124 [ <circular-clumps> ] map-like ; inline