Skip to content

Instantly share code, notes, and snippets.

@thushan
Created April 29, 2015 23:37
Show Gist options
  • Save thushan/48527fa7a642fc21813c to your computer and use it in GitHub Desktop.
Save thushan/48527fa7a642fc21813c to your computer and use it in GitHub Desktop.
Levenshtein distance calculation between two words. See http://en.wikipedia.org/wiki/Levenshtein_distance
let levenshtein word1 word2 =
let preprocess = fun (str : string) -> str.ToLower().ToCharArray()
let chars1, chars2 = preprocess word1, preprocess word2
let m, n = chars1.Length, chars2.Length
let table : int[,] = Array2D.zeroCreate (m + 1) (n + 1)
for i in 0..m do
for j in 0..n do
match i, j with
| i, 0 -> table.[i, j] <- i
| 0, j -> table.[i, j] <- j
| _, _ ->
let delete = table.[i-1, j] + 1
let insert = table.[i, j-1] + 1
let substitute =
if chars1.[i - 1] = chars2.[j - 1]
then table.[i-1, j-1]
else table.[i-1, j-1] + 2
table.[i, j] <- List.min [delete; insert; substitute]
table.[m, n], table
$ levenshtein "Tarragindi" "Holland Park"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment