Re: pass by reference

• To: mathgroup at smc.vnet.net
• Subject: [mg93724] Re: pass by reference
• From: Szabolcs Horvát <szhorvat at gmail.com>
• Date: Mon, 24 Nov 2008 04:12:39 -0500 (EST)
• Organization: University of Bergen
• References: <gg8p9s\$jsp\$1@smc.vnet.net>

```juan flores wrote:
> Dear all,
>
> How do you pass by reference in Mathematica?

You don't.  Mathematica doesn't work that way.

>
> 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.
>

My advice is: don't force a programming style on Mathematica that
doesn't fit it.  This is just going to cause you a lot of frustration.

I can't provide alternatives, though, since you did not say what is the
real problem that you're trying to solve (instead you made up an
artificial programming problem).

ClearAll[push, pop]

SetAttributes[push, HoldRest]
push[el_, stack_] := PrependTo[stack, el]

SetAttributes[pop, HoldAll]
pop[stack_] := With[{el = First[stack]},
stack = Rest[stack];
el]

```

• Prev by Date: Re: pass by reference
• Next by Date: Re: FFT in Mathematica
• Previous by thread: Re: pass by reference
• Next by thread: Re: pass by reference