Created
February 11, 2018 21:07
-
-
Save mkcor/18ed375fa53be5bfc3a70203cf4c381d to your computer and use it in GitHub Desktop.
Start code that takes some Lisp code, returns its abstract syntax tree, and runs it.
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 | |
import ast | |
lisp_code = '(first (list 1 (+ 2 3) 9))' | |
# find innermost list | |
# get its abstract syntax tree (AST) | |
# (run it) | |
# find second innermost list and iterate | |
# ... | |
# run AST of lisp_code | |
def make_ast(cs): | |
"""Return AST for flat list.""" | |
l = cs.strip('()').split() | |
l = [l[0]] + [ast.literal_eval(i) for i in l[1:]] | |
assert isinstance(l[0], str) | |
return l | |
def run_sum(l): | |
"""Return sum of non-first elements.""" | |
assert l[0] == '+' | |
return sum(l[1:]) | |
def run_list(l): | |
"""Return list of non-first elements.""" | |
assert l[0] == 'list' | |
return [i for i in l[1:]] | |
if __name__ == "__main__": | |
# execute only if run as a script | |
char_str = '(+ 2 3)' # innermost list | |
li = make_ast(char_str) | |
print('Call our implementation of sum function on innermost list:') | |
s = run_sum(li) | |
print(s) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment