I am very new to haskell and I am trying to understand the methodology used to create Monadic parser in this document https://www.cs.nott.ac.uk/~gmh/pearl.pdf
Instead of following it exactly, I am trying to do it a little bit differently in order to understand it correctly, therefore, I ended up with this code
newtype Parser a = Parser (String -> Maybe (a, String))
item :: Parser Char
item = Parser (\cs -> case cs of
"" -> Nothing
(c:cs) -> Just (c, cs))
getParser (Parser x) = x
instance Monad Parser where
return x = Parser (\cs -> Just (x,cs))
(Parser p) >>= f = Parser (\cs -> let result = p cs in
case result of
Nothing -> Nothing
Just (c,cs') -> getParser (f c) cs')
takeThreeDropSecond :: Parser (Char, Char)
takeThreeDropSecond = do
c1 <- item
item
c2 <- item
return (c1, c2)
This seems to be working, but I am having hard time following what is going on in do notation.
For example; in c1 <- item
, what is assigned to c1
? Is it the function that is contained in Parser
type, or result of that computation, or what else? Moreover, second line in do notation is just item
, so does it just run item
but doesn't assign the result? And finally, what does return (c1,c2)
produce? Is it Parser (String -> Maybe ((c1, c2)), String)
or just Just (c1, c2)
?