Re: Re: Question involving scope/recursion/arguments
- To: mathgroup at smc.vnet.net
- Subject: [mg27767] Re: [mg27731] Re: Question involving scope/recursion/arguments
- From: David Withoff <withoff at wolfram.com>
- Date: Wed, 14 Mar 2001 04:07:11 -0500 (EST)
- Sender: owner-wri-mathgroup at wolfram.com
> One common example of what I'm trying to do is the quicksort algorithm -
> where a list or an array is sorted in place recursively. I am finding greta
> frustration trying to find the Mathematica technique which would result in
> behavior similar to passing an argument by reference or a pointer to an
> argument.
>
> I can do this with a global variable, but then, as far as I can see, I'm
> bound to passing in an argument with the same name as the global variable
> I'm using (else I have to make a copy of the variable unless Mathematica
> will allow two variables to reference the same data in memory - I'm
> obviously reasonably new to Mathematica).
>
> Eric
Call-by-reference in Mathematica (or any programming language) requires
holding function arguments unevaluated. For example, assignment functions
are call-by-reference operations, and hold the left side of the assignment
unevaluated. quicksort can be written
quicksort[data_, i_, j_] := Module[{pivot},
If[i < j,
pivot = partition[Unevaluated[data], i, j];
quicksort[Unevaluated[data], i, pivot - 1];
quicksort[Unevaluated[data], pivot + 1, j]
]
]
and used
quicksort[Unevaluated[data], 1, Length[data]]
if quicksort and partition don't have the HoldFirst
attribute, or
SetAttributes[quicksort, HoldFirst]
quicksort[data_, i_, j_] := Module[{pivot},
If[i < j,
pivot = partition[data, i, j];
quicksort[data, i, pivot - 1];
quicksort[data, pivot + 1, j]
]
and used
quicksort[data, i, Length[data]
if they do, where partition is the usual quicksort partition step
(left as an exercise to the reader).
Dave Withoff
Wolfram Research