PLAI那些事07 FAE with Deferred Substitution

FAE-parse : 一成不變

FAE-Value : interp的最終轉讓值

;;numV: value 
;;closureV: param-FAE(或value,或function) pair list
(define-type FAE-Value
  [numV (n number?)]
  [closureV (param symbol?) (body FAE?) (ds DefrdSub?)])

DefrdSub : 傳達environment

;;之前WAE中使用的DefrdSub只用於with,可是在這裏with的置換和function call這兩種做用是同時進行的。因此在FAE-Value上有numV和closureV兩種組合。
(define-type DefrdSub
  [mtSub]
  [aSub (name symbol?) (value FAE-Value?) (ds DefrdSub?)])

lookup : symbol DefrdSub -> FAE-Value

(define (lookup name ds)
  (type-case DefrdSub ds
    [mtSub () (error 'lookup "free variable")]
    [aSub (x val rest) (if (symbol=? x name)
                           val
                           (lookup name rest))]))

interp : FAE - >FAE 修改成 FAE DefrdSub -> FAE-Value

;;若是interp f ds中有f存在於ds中,在id (s)的lookup s ds中,closureV從新出現,那麼f-val中的closureV a-val將成爲numV。

;;app中aSub爲何不是mtsub ?F1WAE with deferred substitution中是mtSub的理由是static scope。這裏是由ds決定lambda函數的scope。這時的ds不是叫app時的ds,而是至關於function被定義時scope的ds。

;;若是(closureV-ds - f-val)中加入ds,就會成爲dynamic scope。
(define (interp fae ds)
  (type-case FAE fae
    [num (n) (numV n)]
    [add (l r) (num+ (interp l ds) (interp r ds))]
    [sub (l r) (num- (interp l ds) (interp r ds))]
    [id (s) (lookup s ds)]
    [fun (x b) (closureV x b ds)]
    [app (f a) (local [(define f-val (interp f ds))
                       (define a-val (interp a ds))]
                  (interp (closureV-body f-val)
                          (aSub (closureV-param f-val)
                                a-val
                                (closureV-ds f-val))))]))
相關文章
相關標籤/搜索