1

Do you have any advice for writing a Lisp dialect/interpreter in Python? I'd like to start off with just several basic commands, like set, print, and define or something.

2 Answers 2

6

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.

Sign up to request clarification or add additional context in comments.

Comments

4

Check out How to Write a Lisp Interpreter in Python.

2 Comments

Sorry, I mixed up the link. Check it out again now.
I know, I am good friends with Peter. He's my neighbour, actually. Advice? He's been busy lately.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.