Skip to content

Instantly share code, notes, and snippets.

@justinfay
Last active August 29, 2015 14:22
Show Gist options
  • Select an option

  • Save justinfay/daba2830ea252b578539 to your computer and use it in GitHub Desktop.

Select an option

Save justinfay/daba2830ea252b578539 to your computer and use it in GitHub Desktop.
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