R behaves as if all arguments were passed by value – i.e. as if the callee gets an entirely separate copy of each argument, including arrays. Of course, actually copying arrays like this would be a performance disaster; to try to recover some efficiency, R uses a technique called "copy on write <http://en.wikipedia.org/wiki/Copy-on-write>". This still involved an unfortunate amount of bookkeeping but it's better than actually copying. Matlab also works like this. Julia works differently: arguments to functions are passed by sharing <http://julia.readthedocs.org/en/latest/manual/functions/#argument-passing-behavior>. This is the way that Python, Ruby, Perl, Lisp and Java all work, so it's not exactly controversial, but it is different than R and Matlab.
The other issue about bindings is in our FAQ: http://julia.readthedocs.org/en/latest/manual/faq/#i-passed-an-argument-x-to-a-function-modified-it-inside-that-function-but-on-the-outside-the-variable-x-is-still-unchanged-why On Sun, Jun 29, 2014 at 3:02 PM, Tomas Krehlik <[email protected]> wrote: > First of all, in the first > > *julia> ftest = function(x) * > * x[2] = 0 * > * return x* > * end* > *(anonymous function)* > > you are modifying the passed object x. > > But in the second one you are resetting x. > > *ftest2 = function(x) * > * x = x[[2,1]] * > * return x* > *end* > > I think the optimal solution to this heavily depends on the problem you > are facing, but generally deepcopy copies fully the object, which means > will allocate more memory. > > Also one weird thing that I came across lately, which is not obvious in > the light of the previous is that if you take your first function and pass > to it a row or column of a matrix, the original matrix won't be modified. > Try for example ftest(eye(2)[:,2]). > > Hope this reply helped. > > On Sunday, 29 June 2014 11:24:42 UTC+2, Stéphane Laurent wrote: >> >> Hello, >> >> As a R user I am a little puzzled by this behaviour: >> >> *julia> ftest = function(x) * >> * x[2] = 0 * >> * return x* >> * end* >> *(anonymous function)* >> >> *julia> y = [1,2]* >> *2-element Array{Int64,1}:* >> * 1* >> * 2* >> >> *julia> ftest(y)* >> *2-element Array{Int64,1}:* >> * 1* >> * 0* >> >> *julia> y* >> *2-element Array{Int64,1}:* >> * 1* >> * 0* >> >> >> In R, this function doesn't modify the variable passed in the argument: >> >> *> f <- function(x){ x[2] <- 0; return(x)}* >> *> y=1:2* >> *> f(y)* >> *[1] 1 0* >> *> y* >> *[1] 1 2* >> >> Please could you tell me whether this is a good solution : >> >> *ftest = function(x) * >> * x = deepcopy(x)* >> * x[2] = 0 * >> * return x* >> *end* >> >
