3 ms·
> No, a parser is not an functor, an applicative or god forbid a monad. Here is my Parser and its Functor, Applicative and Monad definitions: newtype Pars
by mrkeen 3y ago
> No, a parser is not an functor, an applicative or god forbid a monad.
Here is my Parser and its Functor, Applicative and Monad definitions:
newtype Parser s a =
Parser { runParser :: s -> Either String (s, a) }
instance Functor (Parser s) where
fmap :: (a -> b) -> Parser s a -> Parser s b
fmap f (Parser run) = Parser $ \s -> (\(s',a) -> (s', f a)) <$> run s
instance Applicative (Parser s) where
pure :: a -> Parser s a
pure x = Parser $ \s -> Right (s, x)
(<*>) :: Parser s (a -> b) -> Parser s a -> Parser s b
pf <*> px = Parser $ \s ->
case runParser pf s of
Left l -> Left l
Right (s', f) ->
case runParser px s' of
Left l -> Left l
Right (ss', a) -> Right (ss', f a)
instance Monad (Parser s) where
return :: a -> Parser s a
return = pure
(>>=) :: Parser s a -> (a -> Parser s b) -> Parser s b
ma >>= f = Parser $ \s ->
case runParser ma s of
Left l -> Left l
Right (s', a) -> runParser (f a) s'