1 ! Copyright (C) 2005, 2010 Slava Pestov, Joe Groff.
2 ! See http://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
77 [ [ first-unsafe 1 ] [ setup-each [ + ] 2dip ] bi ] dip
78 '[ @ _ keep swap ] (all-integers?) nip
82 : all-equal? ( seq -- ? ) [ = ] monotonic? ;
84 : all-eq? ( seq -- ? ) [ eq? ] monotonic? ;
87 { from integer read-only }
88 { to integer read-only }
91 INSTANCE: circular-slice virtual-sequence
93 M: circular-slice equal? over circular-slice? [ sequence= ] [ 2drop f ] if ;
95 M: circular-slice hashcode* [ sequence-hashcode ] recursive-hashcode ;
97 M: circular-slice length [ to>> ] [ from>> ] bi - ; inline
99 M: circular-slice virtual-exemplar seq>> ; inline
101 M: circular-slice virtual@
102 [ from>> + ] [ seq>> ] bi [ length rem ] keep ; inline
104 C: <circular-slice> circular-slice
106 TUPLE: circular-clumps
110 INSTANCE: circular-clumps sequence
112 M: circular-clumps length
113 seq>> length ; inline
115 M: circular-clumps nth
116 [ n>> over + ] [ seq>> ] bi <circular-slice> ; inline
118 : <circular-clumps> ( seq n -- clumps )
119 circular-clumps new-groups ; inline
121 : circular-clump ( seq n -- array )
122 [ <circular-clumps> ] map-like ; inline