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


前言

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

计划

  • Define a environment
  • Implement lookup in environment

codes

  1. Define a environment as list.
(define-type Binding
  [bind (name : symbol) (val : number)])
(define-type-alias Env (listof Binding))
  1. Implement lookup in environment
; DONE : Define lookup
(define (lookup [for : symbol] [env : Env]) : number
  (cond
    [(empty? env) (error 'lookup "name not found")]
    [(equal? for (bind-name (first env))) (bind-val (first env))]
    [else (lookup for (rest env))]))
  1. Test cases
(test (lookup 'a (list (bind 'a 5))) => 5)
(test (lookup 'b (list (bind 'a 5) (bind 'b 6))) => 6)
(test (lookup 'a (list (bind 'a 5) (bind 'b 6))) => 5)

总结

通过实现环境的定义和查找功能,我们为解释器添加了状态管理的能力。环境作为绑定的列表,允许我们在运行时存储和检索变量值。