1 ! Copyright (C) 2005, 2008 Slava Pestov.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: kernel arrays sequences math namespaces strings io
4 vectors words assocs combinators sorting unicode.case
5 unicode.categories math.order ;
8 : (fuzzy) ( accum ch i full -- accum i ? )
11 [ swap push ] 2keep 1+ t
16 : fuzzy ( full short -- indices )
17 dup length <vector> -rot 0 -rot
18 [ -rot [ (fuzzy) ] keep swap ] all? 3drop ;
20 : (runs) ( runs n seq -- runs n )
24 [ drop ] [ nip V{ } clone pick push ] if
29 : runs ( seq -- newseq )
30 V{ V{ } } [ clone ] map over first rot (runs) drop ;
32 : score-1 ( i full -- n )
34 { [ over zero? ] [ 2drop 10 ] }
35 { [ 2dup length 1- number= ] [ 2drop 4 ] }
36 { [ 2dup >r 1- r> nth Letter? not ] [ 2drop 10 ] }
37 { [ 2dup >r 1+ r> nth Letter? not ] [ 2drop 4 ] }
41 : score ( full fuzzy -- n )
43 [ [ length ] bi@ - 15 swap [-] 3 /f ] 2keep
45 [ 0 [ pick score-1 max ] reduce nip ] keep
52 : rank-completions ( results -- newresults )
54 [ 0 [ first max ] reduce 3 /f ] keep
55 [ first < ] with filter
58 : complete ( full short -- score )
59 [ dupd fuzzy score ] 2keep
61 dupd fuzzy score max ;
63 : completion ( short candidate -- result )
64 [ second >lower swap complete ] keep first 2array ;
66 : completions ( short candidates -- seq )
70 >r >lower r> [ completion ] with map
74 : string-completions ( short strs -- seq )
75 [ dup ] { } map>assoc completions ;
77 : limited-completions ( short candidates -- seq )
78 completions dup length 1000 > [ drop f ] when ;