-
-
Save cdunklau/59358228ec4bc8ee6fa3f1e5e97f3557 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ParsePair: | |
def __init__(self, result, rest): | |
self.result = result | |
self.rest = rest | |
_DIGITS = frozenset('0123456789') | |
def digits_parser(string): | |
if len(string) < 1: | |
return [] | |
digits = [] | |
charstack = list(reversed(string)) | |
while charstack: | |
c = charstack.pop() | |
if c in _DIGITS: | |
digits.append(c) | |
else: | |
charstack.append(c) | |
break | |
if not digits: | |
return [] | |
return [ ParsePair(''.join(digits), ''.join(reversed(charstack))) ] | |
def char(c): | |
def char_parser(string): | |
if len(string) < 1: | |
return [] | |
c_candidate, rest = string[0], string[1:] | |
if c_candidate == c: | |
return [ ParsePair(c_candidate, rest) ] | |
return [] | |
return char_parser | |
def sequence(first_parser, second_parser): | |
def combined_parser(string): | |
return [second_parser(pp.rest) for pp in first_parser(string)] | |
return combined_parser | |
def bind(parser, kf): | |
def bound_parser(string): | |
pairs = parser(string) | |
next_pairs = [kf(pp.result)(pp.rest) for pp in pairs] | |
return next_pairs | |
return bound_parser | |
def pure(ready_result): | |
return lambda string: [ ParsePair(ready_result, string) ] | |
def item_parser(string): | |
if len(string) < 1: | |
return [] | |
return [ ParsePair(string[0], string[1:]) ] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment