Join Nostr
2026-07-11 08:29:00 UTC

yfaming on Nostr: # (How to Write a (Lisp) Interpreter (in Python)) ...

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

https://www.norvig.com/lispy.html

跟着过了一遍,代码也敲了。感觉很过瘾。

精心选择了 Scheme 语法的一个子集,使得 parse 非常简单。
支持的语法其实只有一个:`exp := (op exp...)`。
```
Exp = Symbol | Number | List
List = (Exp ...)
```

它充分利用了 Python 的类型来表示 Symbol (str),Number (int|float),List (list)。
parse 时,去掉括号,但以 List 形式保留了树形结构。以此为 ast。

在 ast 基础上进行 eval。本质上是 ast walking interpret。
基于 dict 构建了求值环境 Env。并且将 Env 串起来,形成嵌套作用域,从而方便地支持了闭包。