]> gitweb.factorcode.org Git - factor.git/blob - core/splitting/splitting.factor
Merge branch 'master' of git://factorcode.org/git/factor
[factor.git] / core / splitting / splitting.factor
1 ! Copyright (C) 2005, 2009 Slava Pestov.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: kernel math make strings arrays vectors sequences
4 sets math.order accessors ;
5 IN: splitting
6
7 : ?head ( seq begin -- newseq ? )
8     2dup head? [ length tail t ] [ drop f ] if ;
9
10 : ?head-slice ( seq begin -- newseq ? )
11     2dup head? [ length tail-slice t ] [ drop f ] if ;
12
13 : ?tail ( seq end -- newseq ? )
14     2dup tail? [ length head* t ] [ drop f ] if ;
15
16 : ?tail-slice ( seq end -- newseq ? )
17     2dup tail? [ length head-slice* t ] [ drop f ] if ;
18
19 : (split1) ( seq subseq -- start end ? )
20     tuck swap start dup
21     [ swap [ drop ] [ length + ] 2bi t ]
22     [ 2drop f f f ]
23     if ;
24
25 : split1 ( seq subseq -- before after )
26     [ drop ] [ (split1) ] 2bi
27     [ [ over ] dip [ head ] [ tail ] 2bi* ]
28     [ 2drop f ]
29     if ;
30
31 : split1-slice ( seq subseq -- before-slice after-slice )
32     [ drop ] [ (split1) ] 2bi
33     [ [ over ] dip [ head-slice ] [ tail-slice ] 2bi* ]
34     [ 2drop f ]
35     if ;
36
37 : split1-last ( seq subseq -- before after )
38     [ <reversed> ] bi@ split1 [ reverse ] bi@
39     dup [ swap ] when ;
40
41 : split1-last-slice ( seq subseq -- before-slice after-slice )
42     [ <reversed> ] bi@ split1-slice [ <reversed> ] bi@
43     [ f ] [ swap ] if-empty ;
44
45 : (split) ( separators n seq -- )
46     3dup rot [ member? ] curry find-from drop
47     [ [ swap subseq , ] 2keep 1+ swap (split) ]
48     [ swap dup zero? [ drop ] [ tail ] if , drop ] if* ; inline recursive
49
50 : split, ( seq separators -- ) 0 rot (split) ;
51
52 : split ( seq separators -- pieces ) [ split, ] { } make ;
53
54 : string-lines ( str -- seq )
55     dup "\r\n" intersects? [
56         "\n" split [
57             but-last-slice [
58                 "\r" ?tail drop "\r" split
59             ] map
60         ] keep peek "\r" split suffix concat
61     ] [
62         1array
63     ] if ;