Services & Resources / Wolfram Forums / MathGroup Archive

MathGroup Archive 2008

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

Search the Archive

Re: pass by reference

  • To: mathgroup at
  • Subject: [mg93735] Re: pass by reference
  • From: Albert Retey <awnl at>
  • Date: Mon, 24 Nov 2008 04:14:37 -0500 (EST)
  • References: <gg8p9s$jsp$>


> How do you pass by reference in Mathematica?

What you can do is to prevent arguments from being evaluated with using
one of the Hold attributes for the functions. So you can pass symbols
instead of the expression they evaluate to, which effectively is like
pass by reference. These are the definitions you could make for your

ClearAll[Push, Pop]

SetAttributes[{Push, Pop}, HoldFirst]

Push[stack_, val_] := PrependTo[stack, val]

Pop[stack_] :=
  Module[{r = First[stack]}, stack = Rest[stack]; r];

And this is how you could use these definitions:

stack = {1, 2, 3}

Push[stack, 5]



You still could give any kind of expression as first argument, but then
the evaluations of the RHS will fail, e.g.:


so it makes sense to restrict the function definitions to only accept
symbols as arguments:

Push[stack_Symbol, val_] := PrependTo[stack, val]

Pop[stack_Symbol] :=
  Module[{r = First[stack]}, stack = Rest[stack]; r];



  • Prev by Date: Re: pass by reference
  • Next by Date: ContourPlot and ColorFunction Opacity
  • Previous by thread: Re: pass by reference
  • Next by thread: Re: pass by reference