Created
December 12, 2013 02:09
-
-
Save yabberyabber/7922169 to your computer and use it in GitHub Desktop.
Wouldn't it be fun to write a lisp interpretor in python?
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
def car(x): | |
return x[0] | |
def cdr(x): | |
return x[1:] | |
#define some things that we can do in our arithmatic language | |
def plus(x): | |
if x == []: | |
return 0 | |
else: | |
return car(x) + plus(cdr(x)) | |
def minus(x): | |
return car(x) - plus(cdr(x)) | |
def times(x): | |
if x == []: | |
return 1 | |
else: | |
return car(x) * times(cdr(x)) | |
ops = {'+': plus, '-': minus, '*': times} | |
def atomP(n): | |
return isinstance(n, (int, str)) | |
#takes s-expression tree | |
def eval(exp, i=0): | |
print(" " * i + "calling exp with exp as:", end=" ") | |
print(exp) | |
if exp == []: | |
a = [] | |
print(" " * i + "result:", end=" ") | |
print(a) | |
return a | |
if atomP(car(exp)): | |
print(" " * i + "car is an atom") | |
if isinstance(car(exp), str): | |
print(" " * i + "atom is function") | |
print(" " * i + "car as:", end=" ") | |
print(car(exp)) | |
print(" " * i + "cdr as:", end=" ") | |
print(cdr(exp)) | |
a = ops[car(exp)](eval(cdr(exp), i + 1)) | |
print(" " * i + "result:", end=" ") | |
print(a) | |
return a | |
if isinstance(car(exp), int): | |
print(" " * i + "atom is int") | |
print(" " * i + "car as:", end=" ") | |
print(car(exp)) | |
print(" " * i + "cdr as:", end=" ") | |
print(cdr(exp)) | |
a = [car(exp)] + eval(cdr(exp), i + 1) | |
print(" " * i + "result:", end=" ") | |
print(a) | |
return a | |
else: | |
print(" " * i + "expression is s-expression") | |
print(" " * i + "car as:", end=" ") | |
print(car(exp)) | |
print(" " * i + "cdr as:", end=" ") | |
print(cdr(exp)) | |
a = [eval(car(exp), i + 1)] + eval(cdr(exp), i + 1) | |
print(" " * i + "result:", end=" ") | |
print(a) | |
return a | |
x = ['*', 3, ['+', 3, 4]] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment