[Haskell-cafe] Parsec, updateState, and failure

Jonathan Cast jonathanccast at fastmail.fm
Sat May 31 11:09:53 EDT 2008


On 31 May 2008, at 7:12 AM, Dimitry Golubovsky wrote:

> Hi,
>
> If a parser which updated user state fails, will such update be  
> reverted?
>
> Suppose we have two parsers combined with <|>
>
> p = p1 <|> p2
>
> p1 has the following:
>
> p1 = try $ do
>  ... -- getting something from the input stream
>  updateState (\st -> ...) -- updated state based on what gotten  
> from the input
>  x <- p3 -- p3 should see updated state and return something
>  updateState (\st -> ...) -- updated state again (if p3 succeeded)
>  return x
>
> If p3 fails, p1 fails too (second updateState will not be reached).
> But what will p2 (tried next) see in the user state?

The same thing p1 saw.  You can see the implementation in http:// 
darcs.haskell.org/ghc-6.8/libraries/parsec/Text/ParserCombinators/ 
Parsec/Prim.hs; you want the parsecPlus function.  Furthermore, you  
might note that the GenParser type is defined as

newtype GenParser tok st a = Parser (State tok st -> Consumed (Reply  
tok st a))
runP (Parser p)            = p

data Consumed a         = Consumed a                --input is consumed
                         | Empty !a                  --no input is  
consumed

data Reply tok st a     = Ok !a !(State tok st) ParseError    -- 
parsing succeeded with "a"
                         | Error ParseError                    -- 
parsing failed

data State tok st       = State { stateInput :: [tok]
                                 , statePos   :: !SourcePos
                                 , stateUser  :: !st
                                 }


A parser that fails doesn't deliver a new state for parsecPlus to  
consider using going forward.

jcc



More information about the Haskell-Cafe mailing list