Created
February 12, 2023 23:23
-
-
Save tttardigrado/b3b139c27ecbc7735b2afa15553738f0 to your computer and use it in GitHub Desktop.
Typo fixing suggestions based on the Levenshtein distance
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Data.List (sortOn) | |
import Text.Printf (printf) | |
type Env a = [(String, a)] | |
type Dist a = a -> a -> Int | |
lev :: Dist String | |
lev x "" = length x | |
lev "" y = length y | |
lev (x:xs) (y:ys) = if x == y | |
then lev xs ys | |
else 1 + minimum [lev (x:xs) ys, lev xs (y:ys), lev xs ys] | |
sortEnv :: Env a -> Dist String -> String -> Env a | |
sortEnv env dist str = sortOn (dist str . fst) env | |
put :: String -> a -> Env a -> Env a | |
put str val env = (str, val) : env | |
getS :: Dist String -> Env a -> String -> Either String a | |
getS dist env str = case sortEnv env dist str of | |
[] -> Left $ printf "Couldn't find %s." str | |
(s, x) : _ -> if s == str then Right x else Left msg | |
where msg = printf "Couldn't find %s. Did you mean %s?" str s |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment