Addem
Addem

Reputation: 3919

Haskell: How to implement >>= for a parser

I have the following Parser

newtype Parser a = P (String -> [(a,String)])

and I need to implement the bind on its implementation as a Monad. I have that the return is defined as

instance Monad Parser where
    return v = P (\inp -> [(v,inp)])

To implement p >>= f I know this much: p is a Parser object and f has type declaration

f :: a -> Parser b

So I'm thinking the value of p >>= f needs to be a Parser object which wraps a function. That function's argument is a String. So I'm guessing the function should "open up p", get its function, apply that to the input string, get an object of type [(a, String)], then ... I guess maybe apply f to every first coordinate in each tuple, then use the resulting Parser's function and apply it to the second coordinate ... and make a list of all of those tuples?

At this point I get pretty foggy on whether I got this right and if so, how to do it. Maybe I should write a helper function with type

trans :: [(a,String)] -> (a -> Parser b) -> [(b,String)]

But before getting into that, I wanted to check if my confused description of what I should be doing rings true.

Upvotes: 1

Views: 235

Answers (1)

Dannyu NDos
Dannyu NDos

Reputation: 2498

instance Monad Parser where
    return v = P (\inp -> [(v,inp)])
    P p >>= f = P (\inp -> do
        (x,u) <- p inp
        let P q = f x
        q u
        )

Upvotes: 1

Related Questions