How is set! defined in scheme?

后端 未结 6 1161
囚心锁ツ
囚心锁ツ 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:19

    set! modifies a binding between a symbol and a location (anyting really). Compilers and Interpreters would treat set! differently.

    An interpreter would have an environment which is a mapping between symbols and values. Strictly set! changes the value of the first occurrence of the symbol to point to the result of the evaluation of the second operand. In many implementations you cannot set! something that is not already bound. In Scheme it is expected that the variable is already bound. Reading SICP or Lisp in small pieces and playing with examples would make you a master implementer of interpreters.

    In a compilers situation you don't really need a symbol table. You can keep evaluated operands on a stack and set! need either change what the stack location pointed to or if it's a free variable in a closure you can use assignment conversion. E.g. it could be boxed to a box or a cons.

    (define (gen-counter start delta)
      (lambda ()
         (let ((cur start))
             (set! start (+ cur delta))
             cur)))
    

    Might be translated to:

    (define (gen-counter start delta)
      (let ((start (cons start '()))
         (lambda ()
             (let ((cur (car start)))
                (set-car! start (+ cur delta))
                cur)))))
    

    You might want to read Control-Flow Analysis of Higher-Order Languages where this method is used together with lots of information on compiler technique.

提交回复
热议问题