/Parser.hs Secret
Last active
February 16, 2025 11:41
Simple parser combinators (untested)
This file contains 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
newtype Parser t a = Parser{ runParser :: [t] -> Maybe (a, [t]) } | |
deriving (Functor, Applicative, Alternative, Monad) | |
via StateT [t] Maybe | |
parseToken :: (t -> Maybe a) -> Parser t a | |
parseToken f = Parser \case | |
t:ts -> do | |
x <- f t | |
pure (x, ts) | |
_ -> Nothing | |
token :: Parser t t | |
token = parseToken Just | |
readToken :: Read a => Parser String a | |
readToken = parseToken readMaybe | |
eat :: Eq t => t -> Parser t () | |
eat t = parseToken \t' -> | |
guard (t == t') | |
parseRecords :: String -> Maybe (String, CharacterClass, Int) | |
parseRecords line | |
= fmap fst | |
. flip runParser (words line) | |
$ (,,) <$> (eat "Character:" *> token) | |
<*> (eat "Class:" *> readToken) | |
<*> (eat "Kills:" *> readToken) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment