Blog Archive

Tuesday, February 05, 2008

Parsec as a monad transformer

The proposed Parsec3 package for Haskell has Parsec implemented as a monad transformer, which means I can do things like:

> data MyType
> = Foo
> | Baz
> | Err
> deriving Show

> parseMyType = (string "Foo" >> return Foo)
> <|> (string "Baz" >> return Baz)

> parseNoBaz = callCC $ \k -> do
> result <- parseMyType
> validateResult k result
> return result

> validateResult k Baz = k Err
> validateResult k _ = return ()

> manyNoBaz = parseNoBaz `sepBy` space

> test p s = flip runCont id (runPT p () "test" s)

Then, if I execute test manyNoBaz "Foo Foo Baz Foo" I get the result:

[Foo,Foo,Err,Foo]

This is a contrived example, but I think it's pretty neat.

1 comment:

Font Manager said...

Good reeading

Listening:

Watching:

  • House
  • Ride Back