Compile a simple Lisp interpreter in Python.
This article has two purposes: one is to describe the general method of implementing the computer language interpreter, and the other is to show how to use Python to implement a subset of the Lisp dialect Scheme. I call my interpreter Lispy (lis. py ). A few years ago, I introduced how to use Java to write a Scheme interpreter, and I wrote a version using the Common Lisp Language. This time, my goal is to give a simple and clear demonstration of what Alan Kay said about the "Maxwell's Equations of Software ).
Syntax and semantics of the Scheme subset supported by Lispy
Most computer languages have many syntax conventions (such as keywords, infix operators, Parentheses, operator priorities, dot tags, semicolons, etc.). However, as a member of the Lisp language family, all Scheme syntaxes are based on the prefix list contained in parentheses. This representation seems unfamiliar, but it has the advantages of simplicity and consistency. (Some people say "Lisp" is the abbreviation of "Lots of Irritating Silly Parentheses" -- "a lot of annoying and stupid Parentheses; I think it Is the abbreviation of "Lisp Is Syntactically Pure" -- "Lisp syntax Is Pure .) Consider the following example:
/* Java */if(x.val() > 0) { z = f(a*x.val() + b);}/* Scheme */(if (> (val x) 0) (set! z (f (+ (* a (val x)) b))))
Note that the above exclamation point is not a special character in Scheme; it is just "set! "Part of this name. (In Scheme) Only parentheses are special characters. Similar to (set! X y) a list starting with a special keyword is called a special form in Scheme. The beauty of Scheme is that we only need six special forms, and three other Syntax structures-variables, constants, and process calls.
In this table, var must be a symbol-an identifier similar to x or square-number must be an integer or floating-point number, and other words marked in italic can be any expression. Exp... It indicates zero or multiple times of exp.