coolmenu
coolmenu

Reputation: 11

haskell parsec problem

I am newbie haskell and in lernning parsec lib a example :

nesting :: Parser Int
nesting = do{ char '('
            ; n <- nesting
            ; char ')'
            ; m <- nesting
            ; return (max (n+1) m)
            }
        <|> return 0  

so what's n or m? why n and m is int and greater than 0?

Upvotes: 1

Views: 717

Answers (1)

edon
edon

Reputation: 722

Parsec is a monadic parsing library, so you probably should first introduce yourself to monads and the syntactic sugar that is the do notation.

nesting is a parser which you can see as a computation (monad) with a result of type Int. Whenever you see code like this n <- nesting in a do block, it means run the monad nesting and bind the result to n.

To see how this parser works try running it by hand. For example use the string "()".

It goes like this:

  • Tries the parser in the do block, succeeds parsing '(', runs the parser recursively and binds the result to n.
    • Tries the parser in the do block, fails parsing '(', tries the next parser (return 0) which always succeeds with the value 0.
  • n now has the value 0, because that was the result of running the parser recursively. Next in the do block is the parser char ')', it succeeds, calls the parser again recursively and binds the result to m. Same as above the result in m is 0.

Now the whole result of the computation is max (n+1) m which is 1.

As you can see this parses nested parenthesis, and roughly at the top level n holds the number of '(' parsed, while m holds the number of ')' parsed.

Upvotes: 3

Related Questions