Julia 范围:为什么这个函数会修改一个全局变量? [英] Julia scoping: why does this function modify a global variable?

查看:33
本文介绍了Julia 范围:为什么这个函数会修改一个全局变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Julia 的新人,到目前为止我是它的粉丝.但是从多年的 R 编程经验来看,一些范围规则让我感到困惑.

I'm a relative newcomer to Julia, and so far I am a fan of it. But coming from years of R programming, some scoping rules leave me perplexed.

让我们来看看这个函数.这完全符合我的预期.

Let's take this function. This behaves exactly as I would expect.

function foo1(x)
    y = x
    t = 1
    while t < 1000
      t += 1
      y += 1
    end
    return 42
end

var = 0;
foo1(var)
# 42
var
# 0

但是当对数组做类似的事情时,它充当一个变异函数(在全局范围内修改它的参数!)

But when doing something similar on an array, it acts as a mutating function (modifies it argument in the global scope!)

function foo2(x)
    y = x
    t = 1    
    while t < 1000
      t += 1
      y[1] += 1
    end
    return 42
end

var = zeros(1);
foo2(var)
# 42
var
# 999.0

我意识到我可以通过将第一行更改为 y = copy(x) 来解决这个问题,但是首先出现这种(危险的?)行为的原因是什么?

I realize I can fix this by changing the first line to y = copy(x) , but what is the reason for such a (dangerous?) behaviour in the first place?

推荐答案

我会为此写一个答案,但我认为 John Myles White 已经做得比我以往任何时候都好,所以我将链接到他的博文:

I would write an answer to this, but I think John Myles White has already done it better than I ever could so I'll just link to his blogpost:

https://www.juliabloggers.com/values-vs-bindings-the-map-is-not-the-territory-3/

简而言之 x = 1x[1] = 1 是非常不同的操作.第一个是赋值——即改变变量 x 的绑定——而第二个是调用 setindex! 函数的语法糖,在数组的情况下,它分配给大批.赋值仅更改哪些变量引用哪些对象,而不会修改任何对象.Mutation 只会修改对象,而不会改变哪些变量指向哪些对象.这个答案有更多关于区别的细节:在 Julia 中创建副本= 运算符.

In short x = 1 and x[1] = 1 are very different operations. The first one is assignment—i.e. changing a binding of the variable x—while the second is a syntactic sugar for calling the setindex! function, which, in the case of arrays, assigns to a location in the array. Assignment only changes which variables refer to which objects and never modifies any objects. Mutation only modifies objects and never changes which variables refer to which objects. This answer has a bit more detail about the distinction: Creating copies in Julia with = operator.

这篇关于Julia 范围:为什么这个函数会修改一个全局变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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