sequences.extras: simpler round-robin.

db4
John Benediktsson 2012-05-31 08:17:08 -07:00
parent 5de9ec1b1f
commit 58185a06ce
2 changed files with 10 additions and 12 deletions

View File

@ -72,4 +72,5 @@ IN: sequences.extras.tests
{ 8 } [ 3 iota dup [ 1 + * ] 2map-sum ] unit-test
{ 4 } [ "hello" "jello" [ = ] 2count ] unit-test
{ "ADEBFC" } [ { "ABC" "D" "EF" } round-robin ] unit-test
{ { } } [ { } round-robin ] unit-test
{ "ADEBFC" } [ { "ABC" "D" "EF" } round-robin >string ] unit-test

View File

@ -184,15 +184,12 @@ PRIVATE>
: 2count ( ... seq1 seq2 quot: ( ... elt1 elt2 -- ... ? ) -- ... n )
[ 1 0 ? ] compose 2map-sum ; inline
:: round-robin-as ( seqs exemplar -- newseq )
seqs length :> len
0 0 seqs sum-lengths [
f [
drop dup len >= [ drop 1 + 0 ] when
2dup seqs nth-unsafe ?nth
[ 1 + ] [ dup not ] bi*
] loop
] exemplar replicate-as 2nip ;
: max-lengths ( seq -- n )
[ length ] [ max ] map-reduce ;
: round-robin ( seqs -- newseq )
[ { } ] [ dup first round-robin-as ] if-empty ;
: round-robin ( seq -- newseq )
[ { } ] [
dup [ max-lengths ] [ length ] bi [ iota ] bi@
[ [ 2array ] with map ] curry map concat swap
[ [ first2 ] dip nth-unsafe ?nth ] curry map sift
] if-empty ;