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 ;
7 : ?head ( seq begin -- newseq ? )
8 2dup head? [ length tail t ] [ drop f ] if ;
10 : ?head-slice ( seq begin -- newseq ? )
11 2dup head? [ length tail-slice t ] [ drop f ] if ;
13 : ?tail ( seq end -- newseq ? )
14 2dup tail? [ length head* t ] [ drop f ] if ;
16 : ?tail-slice ( seq end -- newseq ? )
17 2dup tail? [ length head-slice* t ] [ drop f ] if ;
19 : (split1) ( seq subseq -- start end ? )
21 [ swap [ drop ] [ length + ] 2bi t ]
25 : split1 ( seq subseq -- before after )
26 [ drop ] [ (split1) ] 2bi
27 [ [ over ] dip [ head ] [ tail ] 2bi* ]
31 : split1-slice ( seq subseq -- before-slice after-slice )
32 [ drop ] [ (split1) ] 2bi
33 [ [ over ] dip [ head-slice ] [ tail-slice ] 2bi* ]
37 : split1-last ( seq subseq -- before after )
38 [ <reversed> ] bi@ split1 [ reverse ] bi@
41 : split1-last-slice ( seq subseq -- before-slice after-slice )
42 [ <reversed> ] bi@ split1-slice [ <reversed> ] bi@
43 [ f ] [ swap ] if-empty ;
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
50 : split, ( seq separators -- ) 0 rot (split) ;
52 : split ( seq separators -- pieces ) [ split, ] { } make ;
54 : string-lines ( str -- seq )
55 dup "\r\n" intersects? [
58 "\r" ?tail drop "\r" split
60 ] keep peek "\r" split suffix concat