0%

0x06.如何实现一个解释器 in Racket

前言

本文是6. From Substitution to Environments的实验记录。

计划

  • Define a environment
  • Implement lookup in environment

codes

  1. Define a environment as list.

    1
    2
    3
    (define-type Binding
    [bind (name : symbol) (val : number)])
    (define-type-alias Env (listof Binding))
  2. 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))])]))
  3. 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)))))
  4. 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)
  5. 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)
  6. Scope in 3 terms

    1. Is it bound?
    1. where?
    1. Does it has parent scope?