MathGroup Archive 2010

[Date Index] [Thread Index] [Author Index]

Search the Archive

question on passing variable to function by reference


Suppose I want to pass an array to function to be filled in by some value.

We know that one can't write:

---------------------
foo[list_]:=Module[{somevalue=-1},
    list[[All]] = somevalue
]
------------------

Because the default is pass by value.

On way, is to first assign the input to a local symbol, then use the 
local symbol

---------------------
foo[list_]:=Module[{b=list, somevalue=-1},
    b[[All]]=somevalue;
    b
]
--------------------

But in the above, Mathematica allocated a new storage for b, copied list 
to it, and on return, returned 'b'.

I wanted to avoid this extra storage, and use the input, so to make it 
pass by reference, so I wrote

---------------------------
foo2[list_]:=Module[{  somevalue=-1},
     list[[All]]=somevalue;
     list
]
Attributes[foo2]={HoldFirst};
-----------------------------

And now:

list=Table[0,{i,5}];
foo2[list];

list
Out[55]= {-1,-1,-1,-1,-1}

So, this way, it was a pass by reference. Saving storage.

In this above the 'correct' way to handle this, i.e pass by reference? 
Do I need to do something more after I change the Attributes? Any 
possible problems with using this method?


thanks
--Nasser


  • Prev by Date: Is it possible to create custom drawing procedure for my object?
  • Next by Date: NDSolve and hybrid dynamics (Differential Algebraic Equation DAE)
  • Previous by thread: Is it possible to create custom drawing procedure for my object?
  • Next by thread: Re: question on passing variable to function by reference