]> gitweb.factorcode.org Git - factor.git/blob - core/splitting/splitting.factor
aac32784a1f8c49465c72f61b460b7fe31ea66cb
[factor.git] / core / splitting / splitting.factor
1 ! Copyright (C) 2005, 2008 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 -- before after )
20     dup pick start dup [
21         [ >r over r> head -rot length ] keep + tail
22     ] [
23         2drop f
24     ] if ;
25
26 : last-split1 ( seq subseq -- before after )
27     [ <reversed> ] bi@ split1 [ reverse ] bi@
28     dup [ swap ] when ;
29
30 : (split) ( separators n seq -- )
31     3dup rot [ member? ] curry find-from drop
32     [ [ swap subseq , ] 2keep 1+ swap (split) ]
33     [ swap dup zero? [ drop ] [ tail ] if , drop ] if* ; inline recursive
34
35 : split, ( seq separators -- ) 0 rot (split) ;
36
37 : split ( seq separators -- pieces ) [ split, ] { } make ;
38
39 : string-lines ( str -- seq )
40     dup "\r\n" intersect empty? [
41         1array
42     ] [
43         "\n" split [
44             but-last-slice [
45                 "\r" ?tail drop "\r" split
46             ] map
47         ] keep peek "\r" split suffix concat
48     ] if ;