Skip to content
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

Closed
ccorcos opened this issue Jan 9, 2017 · 6 comments
Closed

How to parse an optional token? #11

ccorcos opened this issue Jan 9, 2017 · 6 comments

Comments

@ccorcos
Copy link

ccorcos commented Jan 9, 2017

suppose I have optional arguments: Approve() or Approve(a, b). How would I specify that the arguments are optional?

@ccorcos
Copy link
Author

ccorcos commented Jan 9, 2017

I'm hoping theres something we can do like p.maybe(moreArgs) which returns none and backtracks if theres nothing...

@ccorcos
Copy link
Author

ccorcos commented Jan 10, 2017

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

@sighingnow
Copy link
Owner

We can create a dummy parser which consumes nothing and returns None, then use the try_choice combinator:

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 optional combinator into the library later (maybe with better implementation).

@sighingnow
Copy link
Owner

If you have better solution, feel free to comment here.

@sighingnow sighingnow reopened this Jan 13, 2017
@ccorcos
Copy link
Author

ccorcos commented Jan 17, 2017

That looks fine to me. I'm not terribly familiar with how the internals work but this looks fine.

sighingnow added a commit that referenced this issue Jul 3, 2017
Signed-off-by: Tao He <sighingnow@gmail.com>
@sighingnow
Copy link
Owner

Close as fixed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants