factor/core/splitting/splitting.factor

60 lines
1.7 KiB
Factor
Raw Normal View History

2008-05-05 01:18:35 -04:00
! Copyright (C) 2005, 2008 Slava Pestov.
2007-09-20 18:09:08 -04:00
! See http://factorcode.org/license.txt for BSD license.
USING: kernel math make strings arrays vectors sequences
2008-05-05 01:18:35 -04:00
sets math.order accessors ;
2007-09-20 18:09:08 -04:00
IN: splitting
: ?head ( seq begin -- newseq ? )
2dup head? [ length tail t ] [ drop f ] if ;
: ?head-slice ( seq begin -- newseq ? )
2dup head? [ length tail-slice t ] [ drop f ] if ;
: ?tail ( seq end -- newseq ? )
2dup tail? [ length head* t ] [ drop f ] if ;
: ?tail-slice ( seq end -- newseq ? )
2dup tail? [ length head-slice* t ] [ drop f ] if ;
: split1 ( seq subseq -- before after )
dup pick start dup [
[ [ over ] dip head -rot length ] keep + tail
2007-09-20 18:09:08 -04:00
] [
2drop f
] if ;
: split1-slice ( seq subseq -- before-slice after-slice )
dup pick start dup [
[ [ over ] dip head-slice -rot length ] keep + tail-slice
] [
2drop f
] if ;
: split1-last ( seq subseq -- before after )
2008-03-29 21:36:58 -04:00
[ <reversed> ] bi@ split1 [ reverse ] bi@
2007-09-20 18:09:08 -04:00
dup [ swap ] when ;
: split1-last-slice ( seq subseq -- before-slice after-slice )
[ <reversed> ] bi@ split1-slice [ <reversed> ] bi@
[ f ] [ swap ] if-empty ;
2007-09-20 18:09:08 -04:00
: (split) ( separators n seq -- )
3dup rot [ member? ] curry find-from drop
2007-09-20 18:09:08 -04:00
[ [ swap subseq , ] 2keep 1+ swap (split) ]
2008-07-18 20:22:59 -04:00
[ swap dup zero? [ drop ] [ tail ] if , drop ] if* ; inline recursive
2007-09-20 18:09:08 -04:00
: split, ( seq separators -- ) 0 rot (split) ;
: split ( seq separators -- pieces ) [ split, ] { } make ;
: string-lines ( str -- seq )
dup "\r\n" intersects? [
2007-09-20 18:09:08 -04:00
"\n" split [
2008-05-07 02:38:34 -04:00
but-last-slice [
2007-09-20 18:09:08 -04:00
"\r" ?tail drop "\r" split
] map
] keep peek "\r" split suffix concat
] [
1array
2007-09-20 18:09:08 -04:00
] if ;