Skip to content

Commit

Permalink
Add levenshtein algorithm
Browse files Browse the repository at this point in the history
  • Loading branch information
ErikMcClure committed Jan 5, 2025
1 parent b6d3e86 commit 738a737
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 1 deletion.
43 changes: 43 additions & 0 deletions alicorn-utils.lua
Original file line number Diff line number Diff line change
Expand Up @@ -303,4 +303,47 @@ function M.get_cursor_position(input_file, output_file)
return cursor_line, cursor_column
end

-- https://gist.github.com/Badgerati/3261142
-- Returns the Levenshtein distance between the two given strings
function M.levenshtein(str1, str2)
local len1 = string.len(str1)
local len2 = string.len(str2)
local matrix = {}
local cost = 0

-- quick cut-offs to save time
if len1 == 0 then
return len2
elseif len2 == 0 then
return len1
elseif str1 == str2 then
return 0
end

-- initialise the base matrix values
for i = 0, len1, 1 do
matrix[i] = {}
matrix[i][0] = i
end
for j = 0, len2, 1 do
matrix[0][j] = j
end

-- actual Levenshtein algorithm
for i = 1, len1, 1 do
for j = 1, len2, 1 do
if str1:byte(i) == str2:byte(j) then
cost = 0
else
cost = 1
end

matrix[i][j] = math.min(matrix[i - 1][j] + 1, matrix[i][j - 1] + 1, matrix[i - 1][j - 1] + cost)
end
end

-- return the last value - this is the Levenshtein distance
return matrix[len1][len2]
end

return M
10 changes: 9 additions & 1 deletion evaluator.lua
Original file line number Diff line number Diff line change
Expand Up @@ -237,7 +237,15 @@ enum_desc_srel = setmetatable({
for name, val_type in val_variants:pairs() do
local use_variant = use_variants:get(name)
if use_variant == nil then
error(name .. " is not a valid enum variant! Is this a typo?")
local smallest = 99999999999
local suggest = "[enum has no variants!]"
for n, _ in use_variants:pairs() do
local d = U.levenshtein(name, n)
if d < smallest then
smallest, suggest = d, n
end
end
error(name .. " is not a valid enum variant! Did you mean " .. suggest .. "?")
end
typechecker_state:queue_subtype(
lctx,
Expand Down

0 comments on commit 738a737

Please sign in to comment.