I start discovering parsing in Haskell without any libraries. I created my own data type to implement a couple of type classes.
data Parser a = Parser {
runParser :: String -> Maybe (a, String)
}
instance Functor Parser where
fmap fct (Parser p) = Parser $ \str -> p str >>= \(a, str1) -> Just (fct a, str1)
instance Applicative Parser where
pure a = Parser $ \ s -> Just (a, s)
(Parser p1) <*> (Parser p2) = Parser $ \ str -> do
(f, str1) <- p1 str
(a, str2) <- p2 str1
Just (f a, str2)
instance Alternative Parser where
empty = Parser $ \str -> Nothing
(Parser p1) <|> (Parser p2) = Parser $ \str -> p1 str <|> p2 str
For each classes, I have implemented minimal functions. I understand how they work, but for Applicative I don't understand how <* and *> work. I understand that it's interesting if I want to parse something between delimiters for example
runParser (parseChar 'x' *> parseChar 'a' <* parseChar 'x') "xax"
> Just ('a',"")
I also understand, that it will return "what is in direction of the arrow", so in that case the expression between delimiters. But, what I don't understand is when my string is applied to the first parser, it return a Maybe with parsed data and the rest of the string. How the rest of the string is given to the next parser ?