Skip to content

Instantly share code, notes, and snippets.

@Elvecent
Last active May 19, 2019 08:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Elvecent/9a672fd05b2446b1c8cf36d7d984aca1 to your computer and use it in GitHub Desktop.
Save Elvecent/9a672fd05b2446b1c8cf36d7d984aca1 to your computer and use it in GitHub Desktop.
Monadic parsers
{-# Language DeriveFunctor #-}
module Parser where
newtype Parser a = Parser { parse :: String -> [(a, String)] }
deriving Functor
parserBind :: Parser a -> (a -> Parser b) -> Parser b
parserBind (Parser p) mf = Parser $ \s ->
p s >>= (\(x,s) -> parse (mf x) s)
parserPure :: a -> Parser a
parserPure x = Parser $ \s -> [(x, s)]
instance Applicative Parser where
pure = parserPure
pf <*> p = pf `parserBind` \f ->
p `parserBind` \x ->
parserPure $ f x
instance Monad Parser where
(>>=) = parserBind
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment