]> gitweb.factorcode.org Git - factor.git/blob - extra/rosetta-code/multisplit/multisplit.factor
factor: trim using lists
[factor.git] / extra / rosetta-code / multisplit / multisplit.factor
1 ! Copyright (C) 2020 Alexander Ilin.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: arrays kernel make sequences ;
4
5 IN: rosetta-code.multisplit
6
7 : ?pair ( ? x -- {?,x}/f )
8     over [ 2array ] [ 2drop f ] if ;
9
10 : best-separator ( seq -- pos index )
11     dup [ first ] map infimum '[ first _ = ] find nip first2 ;
12
13 : first-subseq ( separators seq -- n separator )
14     dupd [ swap [ subseq-start ] dip ?pair ] curry map-index sift
15     [ drop f f ] [ best-separator rot nth ] if-empty ;
16
17 : multisplit ( string separators -- seq )
18     '[
19         [ _ over first-subseq dup ] [
20             length -rot cut-slice swap , swap tail-slice
21         ] while 2drop ,
22     ] { } make ;