haskell / attoparsec

A fast Haskell library for parsing ByteStrings
http://hackage.haskell.org/package/attoparsec
Other
512 stars 93 forks source link

wowo w wo = w *> wo <|> wo #96

Closed liyang closed 9 years ago

liyang commented 9 years ago

Careless use could be expensive, but nevertheless I found this combinator useful. Should I submit a patch to Data.Attoparsec.Combinator?

wowo :: Alternative
wowo w wo = w *> wo <|> wo

Otherwise I end up having to name the wo parser, which can be a bit ugly indentation-wise inside a do-block. Also you can use NondecreasingIndentation after wowo (…) $ do

Not happy about the name though. I thought of calling it bono, but I can't live with (or without) having named it bono. :-/

bos commented 9 years ago

I'm sorry, I can't take a patch for a combinator that takes more effort to describe than to write :-(

liyang commented 9 years ago

Apologies, that was a terrible description on my part: wowo is basically what optional does in some other parser monads, e.g. ReadP:

Prelude Control.Applicative> import qualified Text.ParserCombinators.ReadP as R
Prelude Control.Applicative R> let r = R.readP_to_S $ do optional (R.string "bar"); R.string "bar" <* R.eof
Prelude Control.Applicative R> r "bar"
[("bar","")]
Prelude Control.Applicative R> r "barbar"
[("bar","")]

A long time ago, before I became intimately familiar with attoparsec, I was always confused about how to do this, sometimes resorting to trial and error to get a parser that would accept the input. (And probably more that I didn't intend to.) This seems a good illustration of what you need to do to get this kind of backtracking behaviour (even if it is discouraged.)

Would optional' (or optionally) be a better name? I'm not too bothered in either case.