How is set! defined in scheme?

后端 未结 6 1177
囚心锁ツ
囚心锁ツ 2020-12-20 05:45

How would you implement your own set! function in Scheme? A set! function is a destructive procedure that changes a value that is defined taking into account th

6条回答
  •  长情又很酷
    2020-12-20 06:28

    If you are implementing a simple interpreter, then it is not all that hard. Your environment will map from identifiers to their values (or syntactic keywords to their transformers). The identifier->value mapping will need to account for possible value changes. As such:

    (define (make-cell value)
      `(CELL ,value))
    
    (define cell-value cadr)
    (define (cell-value-set! cell value)
      (set-car! (cdr cell) value))
    
    ...
    ((set-stmt? e)
     (let ((name  (cadr e))
           (value (interpret (caddr e) env)))
       (let ((cell (env-lookup name)))
         (assert (cell? cell))
         (cell-value-set! cell value)
         'return-value-for-set!)))
    ...
    

    With two other changes being that when you bind an identifier to a value (like in a let or lambda application) you need to extend the environment with something like:

      (env-extend name (cell value) env)
    

    and also when retrieving a value you'll need to use cell-value.

    Of course, only mutable identifiers need a cell, but for a simple interpreter allocating a cell for all identifier values is fine.

提交回复
热议问题