Skip to content

Instantly share code, notes, and snippets.

@mvaldesdeleon
Created January 25, 2024 23:00
Show Gist options
  • Save mvaldesdeleon/79ae82b4112e414becaa52b8e41b393b to your computer and use it in GitHub Desktop.
Save mvaldesdeleon/79ae82b4112e414becaa52b8e41b393b to your computer and use it in GitHub Desktop.
newtype Position = (Integer, Integer)
data Replacement = {
rStart :: Position,
rEnd :: Position,
rText :: [Char]
}
data Intersect = BEFORE | INSIDE | AFTER
replace :: [Replacement] -> [Char] -> State Position [Char]
replace _ [] = return []
replace [] text = return text
replace (r:rs) (c:cs) = do
cursor <- get
modify (updateCursor c)
case intersect r cursor of
BEFORE -> do
rest <- replace (r:rs) cs
return (c:rest)
INSIDE -> replace (r:rs) cs
AFTER -> do
rest <- replace rs cs
return (rText r) ++ rest
updateCursor :: Char -> Position -> Position
updateCursor c (line, col) =
if c == '\n' then (line + 1, 0)
else (line, col + 1)
intersect :: Replacement -> Position -> Intersect
intersect replacement cursor
| cursor < rStart replacement = BEFORE
| cursor >= rEnd replacement = AFTER
| otherwise = INSIDE
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment