9

I'm trying to translate a grammar written in Haskell using Parsec into Scala's parser combinators.

The translation of the actual matching expressions is pretty straightforward and, at least in my opinion, even a little easier in Scala. What's not at all clear to me is how to handle the statefulness that Parsec passes around using monads.

A Scala parser reads in Input and produces a ParseResult[T].

In contrast, a GenParser in Haskell reads in input and a state and produces another parser. Passing that state around in Scala has me confused.

Does anyone have an example of stateful parsing in Scala that they'd be willing to share?

Todd O'Bryan
  • 2,234
  • 17
  • 30
  • +1 Oooh, I have a stateful parser implemented by passing (implicit, mutable) parameters to the parsers. I really want to have this abstracted into a monad or something. – ziggystar Mar 23 '12 at 10:50
  • I got really excited when I saw Scarpia (https://github.com/runarorama/scarpia) but it looks like it was a good start to a port that never got finished. – Todd O'Bryan Mar 25 '12 at 15:40
  • I've created a set of Parser Combinators that have state in addition to input. It will be a while before I've tested them enough to know if they work and have fiddled with the design enough to be happy with it. Once that happens, I'll post them on github or something. – Todd O'Bryan May 03 '12 at 03:15

1 Answers1

2

The only way I know of to handle state-fullness in Scala Parsers Combinators is through the into method, also known as >> and flatMap (and, yes, you can use it in for-comprehensions). However, it passes state (or, more precisely, parse result) into a parser, and not along the next parsers, which seems to be what you are describing.

Not knowing Haskell's Parsec, it is difficult for me to guess at how that can be used to translate your grammar.

See also this question. There was a very interesting paper about Scala parser combinators, but I was not able to find it. Some spelunking on Scala Lang might turn it up.

Community
  • 1
  • 1
Daniel C. Sobral
  • 295,120
  • 86
  • 501
  • 681