factor/basis/tools/completion/completion.factor

98 lines
2.4 KiB
Factor
Raw Normal View History

! Copyright (C) 2005, 2009 Slava Pestov.
2007-09-20 18:09:08 -04:00
! See http://factorcode.org/license.txt for BSD license.
USING: accessors arrays assocs combinators fry io kernel locals
make math math.order namespaces sequences sorting strings
unicode.case unicode.categories unicode.data vectors vocabs
vocabs.hierarchy words ;
IN: tools.completion
2007-09-20 18:09:08 -04:00
<PRIVATE
: smart-index-from ( obj i seq -- n/f )
rot [ ch>lower ] [ ch>upper ] bi
'[ dup _ eq? [ drop t ] [ _ eq? ] if ] find-from drop ;
PRIVATE>
:: (fuzzy) ( accum i full ch -- accum i ? )
ch i full smart-index-from [
[ accum push ]
[ accum swap 1 + t ] bi
2007-09-20 18:09:08 -04:00
] [
f -1 f
2007-09-20 18:09:08 -04:00
] if* ;
: fuzzy ( full short -- indices )
2009-04-18 22:53:22 -04:00
dup [ length <vector> 0 ] curry 2dip
[ (fuzzy) ] with all? 2drop ;
2007-09-20 18:09:08 -04:00
: (runs) ( runs n seq -- runs n )
[
[
2dup number=
[ drop ] [ nip V{ } clone pick push ] if
1 +
] keep pick last push
2007-09-20 18:09:08 -04:00
] each ;
: runs ( seq -- newseq )
[ V{ } clone 1vector ] dip [ first ] keep (runs) drop ;
2007-09-20 18:09:08 -04:00
: score-1 ( i full -- n )
{
{ [ over zero? ] [ 2drop 10 ] }
{ [ 2dup length 1 - number= ] [ 2drop 4 ] }
{ [ 2dup [ 1 - ] dip nth Letter? not ] [ 2drop 10 ] }
{ [ 2dup [ 1 + ] dip nth Letter? not ] [ 2drop 4 ] }
2008-04-11 13:57:43 -04:00
[ 2drop 1 ]
2007-09-20 18:09:08 -04:00
} cond ;
: score ( full fuzzy -- n )
dup [
2008-03-29 21:36:58 -04:00
[ [ length ] bi@ - 15 swap [-] 3 /f ] 2keep
2007-09-20 18:09:08 -04:00
runs [
[ 0 [ pick score-1 max ] reduce nip ] keep
length * +
2008-01-09 17:36:30 -05:00
] with each
2007-09-20 18:09:08 -04:00
] [
2drop 0
] if ;
: rank-completions ( results -- newresults )
sort-keys <reversed>
[ 0 [ first max ] reduce 3 /f ] keep
[ first < ] with filter
2010-05-17 23:20:46 -04:00
values ;
2007-09-20 18:09:08 -04:00
: complete ( full short -- score )
[ dupd fuzzy score ] 2keep
2008-03-29 21:36:58 -04:00
[ <reversed> ] bi@
2007-09-20 18:09:08 -04:00
dupd fuzzy score max ;
: completion ( short candidate -- result )
[ second swap complete ] keep 2array ;
2007-09-20 18:09:08 -04:00
: completion, ( short candidate -- )
completion dup first 0 > [ , ] [ drop ] if ;
2007-09-20 18:09:08 -04:00
: completions ( short candidates -- seq )
[ ] [
[ [ completion, ] with each ] { } make
rank-completions
] bi-curry if-empty ;
2007-09-20 18:09:08 -04:00
: name-completions ( str seq -- seq' )
[ dup name>> ] { } map>assoc completions ;
: words-matching ( str -- seq )
all-words name-completions ;
: vocabs-matching ( str -- seq )
all-vocabs-recursive filter-vocabs name-completions ;
2009-02-02 16:58:09 -05:00
: chars-matching ( str -- seq )
name-map get keys dup zip completions ;