write lisp dialect
Do you have any advice for writing a 开发者_JS百科Lisp dialect/interpreter in Python? I'd like to start off with just several basic commands, like set
, print
, and define
or something.
There's a fully functional Scheme interpreter in Python here. Its main "eval loop" is just this:
def _eval(self, expr, env):
if DEBUG: print('~~~~ Eval called on %s [%s]' % (expr_repr(expr), type(expr)))
if DEBUG: print('Env:')
if DEBUG: pprint.pprint(env.binding)
# Standard Scheme eval (SICP 4.1.1)
#
if is_self_evaluating(expr):
return expr
elif is_variable(expr):
return env.lookup_var(expr.value)
elif is_quoted(expr):
return text_of_quotation(expr)
elif is_assignment(expr):
env.set_var_value(
var=assignment_variable(expr).value,
value=self._eval(assignment_value(expr), env))
return None
elif is_definition(expr):
env.define_var(
var=definition_variable(expr).value,
value=self._eval(definition_value(expr), env))
return None
elif is_if(expr):
predicate = self._eval(if_predicate(expr), env)
if predicate == Boolean(False):
return self._eval(if_alternative(expr), env)
else:
return self._eval(if_consequent(expr), env)
elif is_cond(expr):
return self._eval(convert_cond_to_ifs(expr), env)
elif is_let(expr):
return self._eval(convert_let_to_application(expr), env)
elif is_lambda(expr):
return Procedure(
args=lambda_parameters(expr),
body=lambda_body(expr),
env=env)
elif is_begin(expr):
return self._eval_sequence(begin_actions(expr), env)
elif is_application(expr):
return self._apply(
self._eval(application_operator(expr), env),
self._list_of_values(application_operands(expr), env))
else:
raise self.InterpretError("Unknown expression in EVAL: %s" % expr)
Pretty much your textbook Scheme eval loop, but this is actual code that works. Bob's code is very clarity-focused, and if you have further questions feel free to ask me.
Check out How to Write a Lisp Interpreter in Python.
精彩评论