Closed liyang closed 9 years ago
I'm sorry, I can't take a patch for a combinator that takes more effort to describe than to write :-(
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.
Careless use could be expensive, but nevertheless I found this combinator useful. Should I submit a patch to
Data.Attoparsec.Combinator
?Otherwise I end up having to name the
wo
parser, which can be a bit ugly indentation-wise inside ado
-block. Also you can useNondecreasingIndentation
afterwowo (…) $ do
…Not happy about the name though. I thought of calling it
bono
, but I can't live with (or without) having named itbono
. :-/