Thursday, October 17, 2013

(How to Write a (Lisp) Interpreter (in Python))

http://norvig.com/lispy.html


What A Language Interpreter Does

A language interpreter has two parts:
  1. Parsing: The parsing component takes an input program in the form of a sequence of characters, verifies it according to thesyntactic rules of the language, and translates the program into an internal representation. In a simple interpreter the internal representation is a tree structure that closely mirrors the nested structure of statements or expressions in the program. In a language translator called a compiler the internal representation is a sequence of instructions that can be directly executed by the computer. As Steve Yegge said"If you don't know how compilers work, then you don't know how computers work." Yegge describes 8 scenarios that can be solved with compilers (or equally with interpreters, or alternatively with Yegge's typical heavy dosage of cynicism.) The Lispy parser is implemented with the function parse.
  2. Execution: The internal representation is then processed according to the semantic rules of the language, thereby carrying out the computation. Execution is implemented with the function eval (note this shadows Python's builtin function).
Here is a picture of the interpretation process and an interactive session showing how parse and eval operate on a short program:

>> program = "(begin (define r 3) (* 3.141592653 (* r r)))"
>>> parse(program)
['begin', ['define', 'r', 3], ['*', 3.141592653, ['*', 'r', 'r']]]
>>> eval(parse(program))
28.274333877
We're using here the simplest possible internal representation, one where Scheme lists, numbers, and symbols are represented as Python lists, numbers, and strings, respectively.


No comments:

Post a Comment