1 ! Copyright (C) 2008, 2009 Slava Pestov.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: kernel layouts math math.order namespaces sequences
4 sequences.private accessors classes.tuple arrays ;
12 : <range> ( a b step -- range )
13 [ over - ] dip [ /i 1 + 0 max ] keep range boa ; inline
15 M: range length ( seq -- n )
18 M: range nth-unsafe ( n range -- obj )
19 [ step>> * ] keep from>> + ;
21 ! For ranges with many elements, the default element-wise methods
22 ! sequences define are unsuitable because they're O(n)
23 M: range equal? over range? [ tuple= ] [ 2drop f ] if ;
25 M: range hashcode* tuple-hashcode ;
27 INSTANCE: range immutable-sequence
29 : twiddle ( a b -- a b step ) 2dup > -1 1 ? ; inline
31 : (a, ( a b step -- a' b' step ) dup [ + ] curry 2dip ; inline
33 : ,b) ( a b step -- a' b' step ) dup [ - ] curry dip ; inline
35 : [a,b] ( a b -- range ) twiddle <range> ; inline
37 : (a,b] ( a b -- range ) twiddle (a, <range> ; inline
39 : [a,b) ( a b -- range ) twiddle ,b) <range> ; inline
41 : (a,b) ( a b -- range ) twiddle (a, ,b) <range> ; inline
43 : [0,b] ( b -- range ) 0 swap [a,b] ; inline
45 : [1,b] ( b -- range ) 1 swap [a,b] ; inline
47 : [0,b) ( b -- range ) 0 swap [a,b) ; inline
49 : range-increasing? ( range -- ? )
52 : range-decreasing? ( range -- ? )
55 : first-or-peek ( seq head? -- elt )
56 [ first ] [ peek ] if ;
58 : range-min ( range -- min )
59 dup range-increasing? first-or-peek ;
61 : range-max ( range -- max )
62 dup range-decreasing? first-or-peek ;
64 : clamp-to-range ( n range -- n )
65 [ range-min max ] [ range-max min ] bi ;
67 : sequence-index-range ( seq -- range )