1 ! Copyright (C) 2005, 2009 Slava Pestov.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: accessors kernel arrays sequences math namespaces
4 strings io fry vectors words assocs combinators sorting
5 unicode.case unicode.categories math.order vocabs
6 tools.vocabs unicode.data ;
9 : (fuzzy) ( accum ch i full -- accum i ? )
12 [ swap push ] 2keep 1+ t
17 : fuzzy ( full short -- indices )
18 dup length <vector> -rot 0 -rot
19 [ -rot [ (fuzzy) ] keep swap ] all? 3drop ;
21 : (runs) ( runs n seq -- runs n )
25 [ drop ] [ nip V{ } clone pick push ] if
30 : runs ( seq -- newseq )
31 V{ V{ } } [ clone ] map over first rot (runs) drop ;
33 : score-1 ( i full -- n )
35 { [ over zero? ] [ 2drop 10 ] }
36 { [ 2dup length 1- number= ] [ 2drop 4 ] }
37 { [ 2dup [ 1- ] dip nth Letter? not ] [ 2drop 10 ] }
38 { [ 2dup [ 1+ ] dip nth Letter? not ] [ 2drop 4 ] }
42 : score ( full fuzzy -- n )
44 [ [ length ] bi@ - 15 swap [-] 3 /f ] 2keep
46 [ 0 [ pick score-1 max ] reduce nip ] keep
53 : rank-completions ( results -- newresults )
55 [ 0 [ first max ] reduce 3 /f ] keep
56 [ first < ] with filter
59 : complete ( full short -- score )
60 [ dupd fuzzy score ] 2keep
62 dupd fuzzy score max ;
64 : completion ( short candidate -- result )
65 [ second >lower swap complete ] keep 2array ;
67 : completions ( short candidates -- seq )
68 [ ] [ [ >lower ] dip [ completion ] with map rank-completions ]
71 : name-completions ( str seq -- seq' )
72 [ dup name>> ] { } map>assoc completions ;
74 : words-matching ( str -- seq )
75 all-words name-completions ;
77 : vocabs-matching ( str -- seq )
78 all-vocabs-seq name-completions ;
80 : chars-matching ( str -- seq )
81 name-map keys dup zip completions ;