Re: pass by reference
- To: mathgroup at smc.vnet.net
- Subject: [mg93741] Re: pass by reference
- From: David Bailey <dave at removedbailey.co.uk>
- Date: Mon, 24 Nov 2008 04:15:42 -0500 (EST)
- References: <gg8p9s$jsp$1@smc.vnet.net>
juan flores wrote:
> Dear all,
>
> How do you pass by reference in Mathematica?
>
> Let us say we want to program push and pop.
> --------
> Push[el_, stack_] := Prepend[stack, el]
> Pop[stack_] := {First[stack], Rest[stack]}
>
> stack = {1, 2, 3}; newel = 5;
>
> stack = Push[newel, stack]
> {5, 1, 2, 3}
>
> {lastel, stack} = Pop[stack]
> {5, {1, 2, 3}}
>
> stack
> {1, 2, 3}
> --------
>
> Code is working, but it is kind of awkward to have to use pure
> functional programming. I have not been able to find the way to pass
> parameters by reference (or name - i.e. macros).
>
> Any pointers/ideas will be greatly appreciated.
>
> Have a good one,
>
> Juan Flores
>
First, I would point out that simply coding a function recursively can
usually remove the need for a push/pop stack.
If you want to write a function that accepts a variable as an argument
and alters it, this is possible by holding the relevant argument:
In[228]:= SetAttributes[more, HoldFirst]
In[233]:= more[x_] := (++x);
In[234]:= x = 66
Out[234]= 66
In[235]:= more[x]
Out[235]= 67
In[236]:= x
Out[236]= 67
This function could even be applied to more general objects - such as
myArray[[k]], but with the proviso that the value of k that will be
used, will be the value at the time of the incrementation (not usually
an issue, but it is worth being aware of).
David Bailey
http://www.dbaileyconsultancy.co.uk