通过计划中的价值混淆 [英] Pass by value confusion in Scheme

查看:104
本文介绍了通过计划中的价值混淆的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

请考虑以下步骤,该步骤取自 SICP :

Consider the following procedure taken from SICP:

 (define (make-withdraw balance)
   (lambda (amount)
     (if (>= balance amount)
         (begin (set! balance 
                      (- balance amount))
                balance)
         "Insufficient funds")))

假设我说:

 (define x (make-withdraw 100))

make-withdraw在名为e2的新环境中返回一个过程((lambda (amount) ... ))(将变量balance的绑定括起来),并将该过程绑定到全局框架中的x.

make-withdraw returns a procedure ((lambda (amount) ... )) inside a new environment called e2 (enclosing the binding for the variable balance), and binds that procedure to x in the global frame.

现在,说我打电话:

 (f x)

其中

 (define (f y) (y 25))

1 .我听说Scheme是按价值传递的.这是否意味着当f创建新环境e3时,它将在y上绑定x值的副本?

1. I've heard that Scheme is pass-by-value. Does this mean that when f creates a new environment e3, it binds a copy of the value of x on y?

2 .也就是说,y(现在)保存的值(在输入f的正文之后)是x保存的lambda的副本吗?

2. That is, the value that y (now) holds (after the body of f is entered) is a copy of the lambda held by x?

3 .因此,我们现在有了两个变量,全局变量xe3中的y,每个变量都包含一个引用e2内部内容的过程?

3. So we now have two variables, x in global and y in e3, each containing a procedure that references things inside e2?

4 .如果我是正确的,那么xy所持有的过程是否像指向e2的指针一样起作用?

4. If I am correct, are the procedures held by x and y acting like pointers to e2?

推荐答案

在按值传递的情况下,将评估函数的参数并将其值绑定到函数参数.

In case of pass by value, arguments to functions are evaluated and their values are bound to the function parameters.

因此,如果参数是表达式,则将对其求值并将值绑定到参数.如果它是绑定到值的标识符,则该值将绑定到参数.

So, if an argument is an expression, it is evaluated and the value is bound to the parameter. If it is an identifier bound to a value, that value is bound to the parameter.

如果一个值很简单,例如一个整数,那么该整数会复制"到新环境中分配的某些内存单元中;如果它更复杂,例如一个闭包(一个编译函数),您可能会认为将该对象的引用"复制到新环境中.

If a value is simple, like an integer, that integer is "copied" in some memory cell allocated inside the new environment, if it is something more complex, like for instance a closure (a compiled function), you can think that the "reference" to that object is copied inside the new environment.

这篇关于通过计划中的价值混淆的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆