1 USING: accessors arrays combinators combinators.short-circuit
2 kernel locals make math math.order sequences sequences.private
8 : levenshtein-step ( insert delete change same? -- next )
9 [ [ 1 + ] bi@ ] 2dip [ 1 + ] unless min min ;
11 : lcs-step ( insert delete change same? -- next )
12 1 -1/0. ? + max max ; ! -1/0. is -inf (float)
14 TYPED:: loop-step ( i j matrix: array old new step -- )
15 i j 1 + matrix nth-unsafe nth-unsafe ! insertion
16 i 1 + j matrix nth-unsafe nth-unsafe ! deletion
17 i j matrix nth-unsafe nth-unsafe ! replace/retain
18 i old nth-unsafe j new nth-unsafe = ! same?
20 i 1 + j 1 + matrix nth-unsafe set-nth-unsafe ; inline
22 : lcs-initialize ( |str1| |str2| -- matrix )
23 iota [ drop 0 <array> ] with map ;
25 : levenshtein-initialize ( |str1| |str2| -- matrix )
26 [ iota ] bi@ [ [ + ] curry map ] with map ;
28 :: run-lcs ( old new init step -- matrix )
29 old length 1 + new length 1 + init call :> matrix
30 old length iota [| i |
31 new length iota [| j |
32 i j matrix old new step loop-step
34 ] each matrix ; inline
38 : levenshtein ( old new -- n )
39 [ levenshtein-initialize ] [ levenshtein-step ]
48 TUPLE: trace-state old new table i j ;
50 : old-nth ( state -- elt )
51 [ i>> 1 - ] [ old>> ] bi nth-unsafe ;
53 : new-nth ( state -- elt )
54 [ j>> 1 - ] [ new>> ] bi nth-unsafe ;
56 : top-beats-side? ( state -- ? )
57 [ [ i>> ] [ j>> 1 - ] [ table>> ] tri nth-unsafe nth-unsafe ]
58 [ [ i>> 1 - ] [ j>> ] [ table>> ] tri nth-unsafe nth-unsafe ] bi > ;
60 : retained? ( state -- ? )
62 [ i>> 0 > ] [ j>> 0 > ]
63 [ [ old-nth ] [ new-nth ] bi = ]
66 : do-retain ( state -- state )
67 dup old-nth retain boa ,
68 [ 1 - ] change-i [ 1 - ] change-j ;
70 : inserted? ( state -- ? )
73 [ { [ i>> zero? ] [ top-beats-side? ] } 1|| ]
76 : do-insert ( state -- state )
77 dup new-nth insert boa , [ 1 - ] change-j ;
79 : deleted? ( state -- ? )
82 [ { [ j>> zero? ] [ top-beats-side? not ] } 1|| ]
85 : do-delete ( state -- state )
86 dup old-nth delete boa , [ 1 - ] change-i ;
88 : (trace-diff) ( state -- )
90 { [ dup retained? ] [ do-retain (trace-diff) ] }
91 { [ dup inserted? ] [ do-insert (trace-diff) ] }
92 { [ dup deleted? ] [ do-delete (trace-diff) ] }
96 : trace-diff ( old new table -- diff )
97 [ ] [ first length 1 - ] [ length 1 - ] tri trace-state boa
98 [ (trace-diff) ] { } make reverse! ;
102 : lcs-diff ( old new -- diff )
103 2dup [ lcs-initialize ] [ lcs-step ] run-lcs trace-diff ;
105 : lcs ( seq1 seq2 -- lcs )
106 [ lcs-diff [ retain? ] filter ] keep [ item>> ] swap map-as ;