简体   繁体   中英

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.

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
        )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM