MathGroup Archive 2008

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

Search the Archive

Re: pass by reference

  • To: mathgroup at smc.vnet.net
  • Subject: [mg93721] Re: pass by reference
  • From: Raffy <raffy at mac.com>
  • Date: Mon, 24 Nov 2008 04:12:07 -0500 (EST)
  • References: <gg8p9s$jsp$1@smc.vnet.net>

On Nov 22, 3:09 am, juan flores <juan... at gmail.com> 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

ClearAll[push, pop];
push[v_, x___] := (v = Join[v, {x}]);
pop[v_] /; Length[v] > 0 := {First[v], v = Rest[v];} // First;
SetAttributes[{push, pop}, HoldFirst];

v = {};

push[v, 1]; ===> v = {1}
push[v, 2, 3]; ===> v = {1, 2, 3}

pop[v] == 1
pop[v] == 2
pop[v] == 3


  • Prev by Date: Re: pass by reference
  • Next by Date: Re: pass by reference
  • Previous by thread: Re: pass by reference
  • Next by thread: Re: pass by reference