Skip to content

Instantly share code, notes, and snippets.

@rojepp
Created April 17, 2012 12:15
Show Gist options
  • Save rojepp/2405633 to your computer and use it in GitHub Desktop.
Save rojepp/2405633 to your computer and use it in GitHub Desktop.
Levenshtein imp vs memo rec
let levenshteinm (s:string) (t:string) =
let c = new Dictionary<_,_>()
let rec memo i j =
match c.TryGetValue((i,j)) with
| true, x -> x
| _ ->
let r =
match (i,j) with
| (i,0) -> i
| (0,j) -> j
| (i,j) ->
if s.[i-1] = t.[j-1] then memo (i-1) (j-1)
else
let d1, d2, d3 = memo (i-1) j, memo i (j-1), memo (i-1) (j-1) in
1 + min d1 (min d2 d3)
c.Add((i,j), r)
r
memo (String.length s) (String.length t)
let levenshteini (a:string) (b:string) : int =
let inline min3 (a:int) b c = min a (min b c)
match a.Length, b.Length with
| 0, m -> m
| n, 0 -> n
| n, m ->
// mutable excuse: it is internal and it avoids Array copy in favor of swap.
let mutable p = Array.init (n+1) id // previous
let mutable d = Array.create (n+1) 0 // current
for j = 1 to m do
let c = b.[j-1]
d.[0] <- j
for i = 1 to n do
let cost = if a.[i-1] = c then 0 else 1
d.[i] <- min3 (d.[i-1] + 1) (p.[i] + 1) (p.[i-1] + cost)
let _d = p
p <- d
d <- _d
p.[n]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment