Created
August 6, 2014 22:18
-
-
Save vilterp/dcbb70fa0c47f6ea3dae 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
# primitives | |
def literal(lit): | |
def parse(input): | |
if len(input) > 0 and input[0] == lit: | |
return input[1:] | |
else: | |
return False | |
return parse | |
def success(): | |
return lambda input: input | |
def failure(): | |
return lambda input: False | |
# first-order combinators | |
def sequence(a, b): | |
def parse(input): | |
a_result = a(input) | |
if isinstance(a_result, str): | |
return b(a_result) | |
else: | |
return False | |
return parse | |
def choice(a, b): | |
def parse(input): | |
a_result = a(input) | |
if isinstance(a_result, str): | |
return a_result | |
else: | |
b_result = b(input) | |
return b_result | |
return parse | |
# second-order combinators (use first order combinators) | |
def choice_of(parsers_list): | |
return reduce(choice, parsers_list) | |
def sequence_of(parsers_list): | |
return reduce(sequence, parsers_list) | |
# conveniences | |
def word(string): | |
return sequence_of(map(literal, string)) | |
def digit(string): | |
return choice_of(map(literal, '0123456789')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment