Hacker News new | past | comments | ask | show | jobs | submit login

Here's a complete PEG parser in 3 lines:

    consume = lambda c: lambda inp: inp[1:] if inp and inp[0] in c else None
    ordered_choice = lambda va,vb: lambda inp: va(inp) or vb(inp)
    concatenate = lambda va,vb: lambda inp: (lambda x: x and vb(x))(va(inp))
Used like this (something I hacked together recently): http://pastebin.com/dUyTZttZ

If you want it to actually do something useful, just wrap the functions with another functions that do what you need.




In va(inp) or vb(inp) couldn't va(inp) succeed with an empty string as the result (at the end) which Python interprets as false, making it mistakenly try vb(x)? I haven't tried to run it.

Also I think c seems misleading as a variable name -- it suggests a single character, but the 'in c' means it's a set of characters.


Yes, that is a bug and yes, those variable names do suck. Thanks for the correction.

    ordered_choice = lambda va,vb: lambda inp: (lambda a,b: a if a or a=="" else b)(va(inp),vb(inp))
Would work, but starts to be so ugly that I'd have to write proper functions and the code would not be 3 lines anymore. ;)


How about

    eat = lambda chars: lambda s: s[1:] if s and s[0] in chars else None
    alt = lambda p, q: lambda s: (lambda r: q(s) if r is None else r)(p(s))
    seq = lambda p, q: lambda s: (lambda r: None if r is None else q(r))(p(s))
going a bit far in the short-names direction, oh well. :) It's too bad Python has this artificial statement/expression distinction.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: