计划并设定!

发布于 2024-08-10 21:22:55 字数 250 浏览 1 评论 0原文

如何通过使用 lambda 参数的函数更改变量的值? 即:

;;definitions
(define test "fails")
(define (experiment input) (set! input "works"))

;;interactions
> test
"fails"
> (experiment test)
> test
"fails"

这似乎失败了..

问候

How can I change the value of a variable via a function that consumes lambda parameter?
Ie:

;;definitions
(define test "fails")
(define (experiment input) (set! input "works"))

;;interactions
> test
"fails"
> (experiment test)
> test
"fails"

This seems to fail..

Regards

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

怪我闹别瞎闹 2024-08-17 21:22:55

您不能 --Scheme“按值”传递所有值,因此在上面的 experiment 函数只是修改其自己的输入参数。要实现这样的功能,您可以使用一个盒子,它是一个显式可变值容器:

(define test (box "fails"))
(define (experiment input) (set-box! input "works"))
(unbox test)
(experiment test)
(unbox test)

如果您确实想要更改变量的值,您可以使用宏:

(define-syntax-rule (experiment input) (set! input "works"))

这会创建experiment 作为宏,这意味着每个 (experiment foo) 形式都被重写为 (set!foo "works")。这可能会产生微妙的后果,因此除非您知道自己在做什么,否则使用它不是一个好主意。 (例如,(实验 2) 将以一种“有趣”的方式失败。)在Scheme中编写宏很容易,但是编写好的宏仍然比编写一个新函数定义。

[请注意,我假设您在此答案中使用 PLT 方案。但如果需要,这两个部分都可以转换为“标准”方案 - 例如,第一部分使用可变的 cons 单元,并将 define-syntax 与 一起使用第二个语法规则。]

You cannot -- Scheme passes all values "by value", so in the above the experiment function simply modifies its own input argument. To get something like this working, you can use a box, which is an explicitly mutable value container:

(define test (box "fails"))
(define (experiment input) (set-box! input "works"))
(unbox test)
(experiment test)
(unbox test)

If you really want to change the value of a variable, you can use a macro:

(define-syntax-rule (experiment input) (set! input "works"))

This creates experiment as a macro, which means that every (experiment foo) form is getting rewritten into (set! foo "works"). This can have subtle consequences, so it's not a good idea to use this unless you know what you're doing. (For example, (experiment 2) will fail in an "interesting" way.) Writing macros in Scheme is easy, but writing good macros is still more difficult than writing a new function definition.

[Note that I'm assuming you're using PLT Scheme in this answer. But both parts can be translated into "standard" Scheme if needed -- for example, use a mutable cons cell for the first, and use define-syntax with syntax-rules for the second.]

梦里梦着梦中梦 2024-08-17 21:22:55

如果你在 Python 中考虑相同的代码,也许会更有意义:

test = "fails"
def experiment(input):
  input = "works"

>>> test
'fails'
>>> experiment(test)
>>> test
'fails'

Maybe it would make more sense if you consider the same code in Python:

test = "fails"
def experiment(input):
  input = "works"

>>> test
'fails'
>>> experiment(test)
>>> test
'fails'
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文