1 ! Copyright (C) 2006 Slava Pestov.
2 ! See http://factorcode.org/license.txt for BSD license.
3 USING: arrays help io kernel math namespaces sequences ;
6 : <matrix> ( m n -- matrix )
7 [ drop 0 <array> ] curry* map ; inline
9 : matrix-> nth nth ; inline
10 : ->matrix nth set-nth ; inline
14 : ->d ( n i j -- ) d get ->matrix ; inline
15 : d-> ( i j -- n ) d get matrix-> ; inline
19 : init-d ( str1 str2 -- )
20 [ length 1+ ] 2apply 2dup <matrix> d set
22 [ dup 0 ->d ] each ; inline
24 : compute-costs ( str1 str2 -- )
26 [ = 0 1 ? ] curry* { } map-as
27 ] curry { } map-as costs set ; inline
29 : levenshtein-step ( i j -- )
31 [ >r 1+ r> d-> 1+ ] 2keep
33 [ costs get matrix-> + min min ] 2keep
34 >r 1+ r> 1+ ->d ; inline
36 : levenshtein-result ( -- n ) d get peek peek ; inline
38 : levenshtein ( str1 str2 -- n )
43 [ levenshtein-step ] curry each