怎么设置!在方案中定义? [英] How is set! defined in scheme?
问题描述
您将如何实现自己的 set!
函数? set!
函数是一种破坏性过程,它会更改考虑到先前值的已定义值.
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 the previous value.
推荐答案
如注释中所述,set!
是Scheme中的原语,必须由实现提供.同样,您不能在大多数编程语言中实现赋值运算符=
.在Common Lisp中,可以扩展setf
(使用setf
-expanders)以允许(setf form value)
处理新的形式.
As noted in the comments, set!
is a primitive in Scheme that must be provided by the implementation. Similarly, you can't implement the assignment operator, =
, in most programming languages. In Common Lisp, setf
can be extended (using setf
-expanders) to allow (setf form value)
to work on new kinds of forms.
因为Scheme的set!
仅修改了变量绑定(例如Common Lisp的setq
),所以仍然值得问一问我们如何实现set-car!
和其他结构修饰符之类的功能.从某种意义上说,这可以看作是对变量的赋值的概括",但是由于词汇变量(以及闭包)足以表示任意复杂的结构,因此它也可以看作是更 specialized 案例.在Scheme中(除了像数组这样的内置图元),对象字段的变异是 specialization ,因为对象可以通过词法闭包来实现,并可以以set!
的方式实现.这是一个典型的练习,展示了如何单独使用词汇闭包来实现结构(例如cons单元格).这是一个显示单值可变单元格实现的示例:
Because Scheme's set!
only modifies variable bindings (like Common Lisp's setq
), it is still worth asking how can we implement functions like set-car!
and other structural modifiers. This could be seen, in one sense, as a generalization of assignment to variables, but because lexical variables (along with closures) are sufficient to represent arbitrarily complex structures, it can also be seen as a more specialized case. In Scheme (aside from built in primitives like arrays), mutation of object fields is a specialization, because objects can be implemented by lexical closures, and implemented in terms of set!
. This is a typical exercise given when showing how structures, e.g., cons cells, can be implemented using lexical closures alone. Here's an example that shows the implementation of single-value mutable cells::
(define (make-cell value)
(lambda (op)
(case op
((update)
(lambda (new-value)
(set! value new-value)))
((retrieve)
(lambda ()
value)))))
(define (set-value! cell new-value)
((cell 'update) new-value))
(define (get-value cell)
((cell 'retrieve)))
基于这些定义,我们可以创建一个以值4
开头的单元格,使用我们的set-value!
将值更新为8
,然后获取新值:
Given these definitions, we can create a cell, that starts with the value 4
, update the value to 8
using our set-value!
, and retrieve the new value:
(let ((c (make-cell 4)))
(set-value! c 8)
(get-value c))
=> 8
这篇关于怎么设置!在方案中定义?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!