Last active
August 29, 2015 14:22
-
-
Save justinfay/daba2830ea252b578539 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| env = {} | |
| def lisp(sexpression): | |
| if isinstance(sexpression, list): | |
| if sexpression[0] == 'quote': | |
| return sexpression[1:] | |
| elif sexpression[0] == 'defn': | |
| env[sexpression[1]] = lisp(sexpression[2]) | |
| # Hack for variable assignment. | |
| return lambda *x: x[1] | |
| return lisp(sexpression[0])(*[lisp(s) for s in sexpression[1:]]) | |
| return env.get(sexpression, sexpression) | |
| if __name__ == "__main__": | |
| import operator | |
| assert 4 == lisp([operator.mul, 2, 2]) | |
| assert 24 == lisp([operator.mul, 2, [operator.mul, 3, 4]]) | |
| assert 'a-b-c' == lisp(['-'.join, ['quote', 'a', 'b', 'c']]) | |
| from random import choice | |
| assert lisp([ | |
| [choice, ['quote', operator.add, operator.sub]], 10, 1]) in [9, 11] | |
| assert 3 == lisp([ | |
| ['defn', 'x', [operator.add, 0, 1]], | |
| ['defn', 'y', 2], | |
| [operator.add, 'x', 'y']]) | |
| assert 10 == lisp([ | |
| ['defn', 'double', lambda x: 2*x], | |
| ['defn', 'pi', '3.14'], | |
| ['double', 5]]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment