Lisp in a single expression
#lisp.py
#
#An interpreter for a simple scheme like lexically
#scoped language implemented as single python expression.
#
#The interpreter is limited to the lambda special form and a
#sum function. The data types supported are positive integers
#and symbols.
#
import re
from itertools import *
iterpreter = (lambda s: (
(lambda g: lambda env, exp: g(g)(env, exp))
(lambda g: (lambda interpret:(
lambda env, exp:{
list:lambda exp:(
(exp[:1]==["lambda"]) and
(lambda env: lambda params:
(lambda nenv: [interpret(nenv, e)
for e in exp[2:]][-1])
(lambda x: dict(zip(exp[1], params)).get(x, False)
or env(x)))(env)
or (lambda pexp: pexp[0](pexp[1:]))([interpret(env, e)
for e in exp])),
str:lambda exp: env(exp), int:lambda exp: exp
}[type(exp)](exp)))(lambda env, exp:g(g)(env, exp))))
(lambda x:{"sum":(lambda params: sum(params))}.get(x, False),
reduce(lambda env, v:
(v==")" and
(lambda:((lambda i:env[:i]+[env[i+1:]])
(len(env)-env[::-1].index("(")-1)))
or (lambda:env+[v]))(),
[(i==2 and int(e[i]) or e[i]) for e, i in
[(e,sum([c*(i is not "") for i, c in zip(e, count())]))
for e in re.findall(r"(\()|(\))|(\d+)|(\w+)",s)]],
[])[0]))
s = "((lambda (a b) (sum a (b))) 1 (lambda () 8))"
v = iterpreter(s)
print v
3 Comments:
That is one fugly piece o' code
Bitchen
That's awesome. Great demonstration of the simple* syntax of Lisp-like languages.
* Conceptually simple.
Post a Comment
<< Home