2017-09-16 18:21:31 -04:00
|
|
|
! Copyright (C) 2017 John Benediktsson, Doug Coleman.
|
|
|
|
! See http://factorcode.org/license.txt for BSD license.
|
2017-09-28 23:19:46 -04:00
|
|
|
USING: combinators kernel math math.order math.statistics
|
|
|
|
sequences sequences.extras sets ;
|
2017-09-16 18:21:31 -04:00
|
|
|
IN: escape-strings
|
|
|
|
|
2017-09-28 23:19:46 -04:00
|
|
|
: find-escapes ( str -- set )
|
|
|
|
[ HS{ } clone 0 0 ] dip
|
|
|
|
[
|
2017-09-16 18:21:31 -04:00
|
|
|
{
|
2017-09-28 23:19:46 -04:00
|
|
|
{ char: \] [ 1 + dup 2 = [ drop over adjoin 0 1 ] when ] }
|
|
|
|
{ char: = [ dup 1 = [ [ 1 + ] dip ] when ] }
|
|
|
|
[ 3drop 0 0 ]
|
2017-09-16 18:21:31 -04:00
|
|
|
} case
|
2017-09-28 23:19:46 -04:00
|
|
|
] each 0 > [ over adjoin ] [ drop ] if ;
|
|
|
|
|
|
|
|
: lowest-missing ( set -- min )
|
|
|
|
members dup [ = not ] find-index
|
|
|
|
[ nip ] [ drop length ] if ;
|
|
|
|
|
|
|
|
: escape-string* ( str n -- str' )
|
|
|
|
char: = <repetition>
|
|
|
|
[ "[" dup surround ] [ "]" dup surround ] bi surround ;
|
2017-09-16 18:21:31 -04:00
|
|
|
|
|
|
|
: escape-string ( str -- str' )
|
2017-09-28 23:19:46 -04:00
|
|
|
dup find-escapes lowest-missing escape-string* ;
|
|
|
|
|
|
|
|
: escape-strings ( strs -- str )
|
|
|
|
dup [ find-escapes ] map
|
|
|
|
[
|
|
|
|
[ lowest-missing ] map
|
|
|
|
[ escape-string* ] 2map concat
|
|
|
|
] [
|
|
|
|
[ ] [ union ] map-reduce
|
|
|
|
] bi
|
|
|
|
dup cardinality 0 = [
|
|
|
|
drop 1
|
2017-09-16 18:21:31 -04:00
|
|
|
] [
|
2017-09-28 23:19:46 -04:00
|
|
|
members minmax nip 2 +
|
|
|
|
] if
|
|
|
|
escape-string* ;
|