Paste number 32161: Levenshtein distance

Index of paste annotations: 1

Paste number 32161: Levenshtein distance
Pasted by: Saizan
2 years, 3 weeks ago
None
Paste contents:
Raw Source | XML | Display As
import Data.List

lev ss ts = fst . last . foldl' aux (zipWith (,) [0..] (' ':ss)) $ zipWith (,) [1..] ts
    where aux ss' (n,t) = let r = (n,' '): zipWith3 aux' r ss' (tail ss')
                              aux' (pr,_) (pc,_) (cc,s) =
                                  let cost = if s == t then 0 else 1
                                  in (minimum [pr+1,pc+cost,cc+1],s)
                          in r

Annotations for this paste:

Annotation number 1: better names, and comments
Pasted by: Saizan
2 years, 3 weeks ago
Paste contents:
Raw Source | Display As
import Data.List
lev :: (Num a, Enum a, Ord a) => [Char] -> [Char] -> a
lev ss ts = fst . last . foldl' nextRow (zip [0..] (' ':ss)) $ zip [1..] ts -- folds on the first column building the rows
    where nextRow ss' (n,t) = let r = (n,' '): zipWith3 takemin r ss' (tail ss') -- build the current row travelling throgh the previous
                                  takemin (pr,_) (pc,_) (cc,s) =                 
                                      let cost = if s == t then 0 else 1         -- comparing each element with the one on the first column
                                      in (minimum [pr+1,pc+cost,cc+1],s)
                              in r

Colorize as:
Show Line Numbers
Index of paste annotations: 1

Lisppaste pastes can be made by anyone at any time. Imagine a fearsomely comprehensive disclaimer of liability. Now fear, comprehensively.