-
Notifications
You must be signed in to change notification settings - Fork 36
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
How to parse an optional token? #11
Comments
I'm hoping theres something we can do like |
here's my solution that i figured out. seems messy though def optional(parser):
@p.generate
def _optional():
r = yield p.times(parser, 0, 1)
if len(r) > 0:
result(r[0])
else:
result(None)
return _optional |
We can create a dummy parser which consumes nothing and returns import parsec as p
def optional(parser):
@p.generate
def dummy():
'''Return None without doing anything.'''
yield p.string('')
return None
return parser ^ dummy ## (^) means try_choice
s = p.string('xx')
print(optional(s).parse('xx')) // xx
print(optional(s).parse('xy')) // None Thanks for your proposal @ccorcos and I will add the |
If you have better solution, feel free to comment here. |
That looks fine to me. I'm not terribly familiar with how the internals work but this looks fine. |
Close as fixed. |
suppose I have optional arguments:
Approve()
orApprove(a, b)
. How would I specify that the arguments are optional?The text was updated successfully, but these errors were encountered: