1 ! Copyright (C) 2005, 2009 Slava Pestov.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: kernel math math.order strings arrays vectors sequences
4 sequences.private accessors fry ;
9 TUPLE: chunking-seq { seq read-only } { n read-only } ;
11 : check-groups ( n -- n )
12 dup 0 <= [ "Invalid group count" throw ] when ; inline
14 : new-groups ( seq n class -- groups )
15 [ check-groups ] dip boa ; inline
17 GENERIC: group@ ( n groups -- from to seq )
19 M: chunking-seq set-nth group@ <slice> 0 swap copy ;
21 M: chunking-seq like drop { } like ;
23 INSTANCE: chunking-seq sequence
25 MIXIN: subseq-chunking
27 M: subseq-chunking nth group@ subseq ;
31 M: slice-chunking nth group@ <slice> ;
33 M: slice-chunking nth-unsafe group@ slice boa ;
35 TUPLE: abstract-groups < chunking-seq ;
37 M: abstract-groups length
38 [ seq>> length ] [ n>> ] bi [ + 1- ] keep /i ;
40 M: abstract-groups set-length
41 [ n>> * ] [ seq>> ] bi set-length ;
43 M: abstract-groups group@
44 [ n>> [ * dup ] keep + ] [ seq>> ] bi [ length min ] keep ;
46 TUPLE: abstract-clumps < chunking-seq ;
48 M: abstract-clumps length
49 [ seq>> length ] [ n>> ] bi - 1+ ;
51 M: abstract-clumps set-length
52 [ n>> + 1- ] [ seq>> ] bi set-length ;
54 M: abstract-clumps group@
55 [ n>> over + ] [ seq>> ] bi ;
59 TUPLE: groups < abstract-groups ;
61 : <groups> ( seq n -- groups )
62 groups new-groups ; inline
64 INSTANCE: groups subseq-chunking
66 TUPLE: sliced-groups < abstract-groups ;
68 : <sliced-groups> ( seq n -- groups )
69 sliced-groups new-groups ; inline
71 INSTANCE: sliced-groups slice-chunking
73 TUPLE: clumps < abstract-clumps ;
75 : <clumps> ( seq n -- clumps )
76 clumps new-groups ; inline
78 INSTANCE: clumps subseq-chunking
80 TUPLE: sliced-clumps < abstract-clumps ;
82 : <sliced-clumps> ( seq n -- clumps )
83 sliced-clumps new-groups ; inline
85 INSTANCE: sliced-clumps slice-chunking
87 : group ( seq n -- array ) <groups> { } like ;
89 : clump ( seq n -- array ) <clumps> { } like ;
91 : monotonic? ( seq quot -- ? )
92 over length 2 < [ 2drop t ] [
94 [ first2-unsafe ] dip call
96 [ 2 <sliced-clumps> ] dip
97 '[ first2-unsafe @ ] all?
101 : all-equal? ( seq -- ? ) [ = ] monotonic? ;
103 : all-eq? ( seq -- ? ) [ eq? ] monotonic? ;