Sunday, April 10, 2011

Lisp interpreter in javascript with jQuery

I started using lisp a few years ago when I wanted to configure the hell out of emacs. After understanding lisp better thanks to some great videos,I built my own lisp interpreter. After two days of work, I had a somewhat working system. The interpreter is not complete however it runs some basic expressions. I guess the code is interesting for CS students trying to understand lisp better. There aren't much comments in the source code but the logic is split into small functions. It shouldn't be too difficult to read. First the lisp string is turned into a list that is passed to the eval-apply cycle and voila.

You can get the source code and add issues on the Google Code page.

Examples of what you can evaluate


(defun fact (x) (if (<= x 1) 1 (* x (fact (- x 1)))))
(fact 5)

Reverse a list

(defun reverse- (x r)
(if (not (car x)) r (reverse- (cdr x) (cons (car x) r))))
(defun reverse (x) (reverse- x (list)))
(reverse (list 1 2 3 4))

Map a list

(defun mapcar (x f)
(if (not (car x)) (list) (cons (f (car x)) (mapcar (cdr x) f))))
(mapcar (list 1 2 3) (lambda (x) (* x x)))

Here's what you can use

car cdr cons
not and or
>= > <= < = eq
+ - * /
nil list setq if lambda defun
There's also a js function. It's to call any javascript function. Try ((js Math.abs) -23)

More javascript lisp interpreters

Some people have written this kind of program before. I have tried them but I couldn't evaluate expressions the way I wanted. You can take a look at the work of Paul M. ParksJoe Ganley or Brian Morearty.

No comments:

Post a Comment