前言
本文是6. From Substitution to Environments
的实验记录。
计划
- Define a environment
- Implement lookup in environment
codes
Define a environment as list.
1
2
3(define-type Binding
[bind (name : symbol) (val : number)])
(define-type-alias Env (listof Binding))Implement lookup in environment
1
2
3
4
5
6
7
8; DONE : Define lookup
(define (lookup [for : symbol] [env : Env]) : number
(cond
[(empty? env) (error 'lookup "name not found")]
[else (cond
[(symbol=? for (bind-name (first env)))
(bind-val (first env))]
[else (lookup for (rest env))])]))Substitution VS Env(1st version)
1
2
3
4
5
6
7
8
9
10
11; Error case in our implementation of Env 1st.
; Our test case equal to
; (define (f1 x) (f2 4))
; (define (f2 y) (+ x y))
; (f1 3)
; If we take a look, we will find error binding that x
; is not binded in f2's definition.
(interp (appC 'f1 (numC 3))
mt-env
(list (fdC 'f1 'x (appC 'f2 (numC 4)))
(fdC 'f2 'y (plusC (idC 'x) (idC 'y)))))detect error occus
1
2
3
4
5; env cross scope
<appC-interp-bind-in-env>
(extend-env (bind (fdC-arg fd)
(interp a env fds))
env)Corret last error binding
1
2
3
4
5; change env to mt-env
<appC-interp-bind-in-env>
(extend-env (bind (fdC-arg fd)
(interp a env fds))
mt-env)Scope in 3 terms
- Is it bound?
- where?
- Does it has parent scope?