Peter Norvig 在他的個人網站上頭,寫了一篇 (How to Write a (Lisp) Interpreter (in Python)) (註), 他寫了約莫 100 行的 python script 來小小模擬一個簡化版的 Lisp Interpreter,看了不禁拍案叫絕。 下頭這個表格截取自他的網頁,指出他這 100 行的程式碼,所實作的 syntax 只有 9 個(註)。
var: variable reference
A symbol is interpreted as a variable name; its value is the variable’s value.
Example: x
number: constant literal
A number evaluates to itself.
Examples: 12 or -3.45e+6
(quote exp): quotation
Return the exp literally; do not evaluate it.
Example: (quote (a b c)) ⇒ (a b c)
(if test conseq alt): conditional
Evaluate test; if true, evaluate and return conseq; otherwise evaluate and return alt.
Example: (if (< 10 20) (+ 1 1) (+ 3 3)) ⇒ 2
(set! var exp): assignment
Evaluate exp and assign that value to var, which must have been previously defined (with a define or as a parameter to an enclosing procedure).
Example: (set! x2 (* x x))
(define var exp): definition
Define a new variable in the innermost environment and give it the value of evaluating the expression exp.
Examples: (define r 3) or (define square (lambda (x) (* x x))).
(lambda (var…) exp): procedure
Create a procedure with parameter(s) named var… and the expression as the body.
Example: (lambda (r) (* 3.141592653 (* r r)))
(begin exp…): sequencing
Evaluate each of the expressions in left-to-right order, and return the final value.
Example: (begin (set! x 1) (set! x (+ x 1)) (* x 2)) ⇒ 4
(proc exp…): procedure call
If proc is anything other than one of the symbols if, set!, define, lambda, begin, or quote then it is treated as a procedure. It is evaluated using the same rules defined here. All the expressions are evaluated as well, and then the procedure is called with the list of expressions as arguments.
Example: (square 12) ⇒ 144
...