Friday, 29 May 2009

Lisp/Scheme interpreter with Python

I wrote a simple Scheme/Lisp like interpreter some time ago. It was just a dumb idea after hours of of Scheme programming at university ;)
It currently supports define, quote, cdr, car, some arithmetical operations and even lambda functions.
If you want to extend the interpreter, you have to bind a new function to the global environment.

For car it looks like that:

def car_builtin(l, env, interp):
assert len(l) == 1
v = l.head().visit(interp, env)
return v.head()

env = Environment()
env.bind("car", Function(car_builtin))

There is a simple example script in the SVN repository to calculate the faculty of a given number.

(define fac
(lambda (f)
(if (< f 2) 1 (* (fac (- f 1)) f))
)
)

Call fac with

(fac 11)

and you you'll get the correct result: 39916800. hehe.

The complete python script can be downloaded from Google Code (http://code.google.com/p/dev-null). It only consists of a few lines of code for scanner, parser, AST, "runtime library" and interpreter.

No comments:

Post a Comment