Re: pass by reference
- To: mathgroup at smc.vnet.net
- Subject: [mg93735] Re: pass by reference
- From: Albert Retey <awnl at gmx-topmail.de>
- Date: Mon, 24 Nov 2008 04:14:37 -0500 (EST)
- References: <gg8p9s$jsp$1@smc.vnet.net>
Hi, > 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 example: 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] Pop[stack] stack You still could give any kind of expression as first argument, but then the evaluations of the RHS will fail, e.g.: Push[{1,3,4}+a^5,5] 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]; hth, albert