Created
October 16, 2018 02:00
-
-
Save pjhades/0046e3900d8739fa5f4c0e632481f398 to your computer and use it in GitHub Desktop.
pretty ugly
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
#!/usr/bin/env python3 | |
def word(w): | |
def f(tokens): | |
return tokens[1:] if len(tokens) > 0 and tokens[0] == w else False | |
return f | |
def zero_or_more(parser): | |
def f(tokens): | |
if len(tokens) == 0: | |
return [] | |
while True: | |
result = parser(tokens) | |
if not result: | |
return tokens | |
tokens = result | |
return tokens | |
return f | |
def then(parser1, parser2): | |
def f(tokens): | |
result = parser1(tokens) | |
if not result: | |
return False | |
return parser2(result) | |
return f | |
def either(parser1, parser2): | |
def f(tokens): | |
result = parser1(tokens) | |
if result is not False: | |
return result | |
return parser2(tokens) | |
return f | |
def ok(parser, s): | |
return True if parser(s.split()) == [] else False | |
if __name__ == "__main__": | |
pretty = word("pretty") | |
its = word("it's") | |
ugly = word("ugly") | |
zero_or_more_pretty = zero_or_more(pretty) | |
parser = then(then(its, zero_or_more_pretty), either(ugly, pretty)) | |
assert(ok(parser, "it's pretty ugly")) | |
assert(ok(parser, "it's pretty pretty")) | |
assert(ok(parser, "it's pretty")) | |
assert(ok(parser, "it's pretty pretty pretty pretty")) | |
assert(ok(parser, "it's ugly")) | |
assert(not ok(parser, "it's bad")) | |
assert(not ok(parser, "it's ugly pretty")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment