Skip to content

Instantly share code, notes, and snippets.

@letsbreelhere
Last active August 29, 2015 14:18
Show Gist options
  • Save letsbreelhere/eabcdfdda3b5189466e8 to your computer and use it in GitHub Desktop.
Save letsbreelhere/eabcdfdda3b5189466e8 to your computer and use it in GitHub Desktop.
import Data.Monoid ((<>))
import Data.Text (Text)
import Text.Parsec
import Text.Parsec.Text
import qualified Data.Text as T
-- Replace all successful parses with a text transformation. E.g.:
-- λ> replaceParsed (read <$> many1 digit) (T.pack . show . (+1)) "foo42bar99baz12quux"
-- "foo43bar100baz13quux"
replaceParsed :: Parser a -> (a -> Text) -> Text -> Text
replaceParsed p f text =
let def = ([],text)
(matches, final) = either (const def) id $ parse (withSeparator p) "" text
in foldr (\(t,parsed) acc -> t <> f parsed <> acc) final matches
-- Parse p repeatedly, returning a list of successful parses with the text
-- preceding it, paired with any trailing text.
withSeparator :: Parser a -> Parser ([(Text, a)], Text)
withSeparator p = do
xs <- many . try $ do
t <- T.pack <$> manyTill anyChar (try $ lookAhead p)
(,) <$> pure t <*> p
finally <- T.pack <$> many anyChar
return (xs, finally)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment