朱莉娅(Julia)作用域:为什么此函数修改全局变量? [英] Julia scoping: why does this function modify a global variable?

查看:97
本文介绍了朱莉娅(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!函数的语法糖,对于数组,该函数分配给数组中的某个位置.分配仅更改哪些变量引用哪些对象,而从不修改任何对象.突变只会修改对象,而不会更改哪个变量引用了哪些对象.这个答案有更多关于区别的细节:在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天全站免登陆