Scheme解释器的输入与调用结果[#50]

run-scheme对表达式列表建立独立环境并求值。阶乘的define简写创建递归过程,列表平方检查递归构造,词法遮蔽检查闭包捕获。这些Example tree的 ⇒ 是构建结果;调用写法为(run-scheme '(...)),列表内的程序由解释器执行。

example. Scheme 阶乘 factorial(5) 的结果为 120[mce-factorial]

(run-scheme '((define (factorial n)
                   (if (= n 0) 1 (* n (factorial (- n 1)))))
                 (factorial 5)))

⇒ 120 · checked

example. Scheme 列表平方的结果为 (1 4 9 16)[mce-map]

(run-scheme '((define (map-square xs)
                   (if (null? xs) '()
                       (cons (* (car xs) (car xs)) (map-square (cdr xs)))))
                 (map-square '(1 2 3 4))))

⇒ (1 4 9 16) · checked

example. Scheme 词法遮蔽的调用结果为 12[mce-lexical]

(run-scheme '((define x 10)
                 (define add-x (lambda (y) (+ x y)))
                 ((lambda (x) (add-x 2)) 100)))

⇒ 12 · checked

12而非102是关键:解释器中的闭包保存定义时的环境,不使用调用者当前的x。每次run都创建新环境。