Re: Call-by-reference from inside a function

• To: mathgroup at smc.vnet.net
• Subject: [mg72596] [mg72596] Re: [mg72568] Call-by-reference from inside a function
• From: Andrzej Kozlowski <akoz at mimuw.edu.pl>
• Date: Thu, 11 Jan 2007 03:40:45 -0500 (EST)

```Sorry, I slightly misinterpreted your post. On re-reading  it
carefully seems to me that what you wanted is rather

s = {1, 2, 3, 4};

SetAttributes[f, HoldAll]

f[p_] := Module[{m = p, i = Random[Integer,
{1, Length[p]}]}, p = Drop[p, {i}]; m[[i]]]
f[s]
3

s
{1, 2, 4}

Andrzej Kozlowski
Oxford, UK

On 9 Jan 2007, at 19:25, Andrzej Kozlowski wrote:

> If I understand you correctly, all you need is something like this:
>
>
> s = {1, 2, 3, 4};
>
> SetAttributes[f, HoldAll]
>
> f[p_] := Module[{i = Random[Integer,
>            {1, Length[p]}]}, p = Drop[p, {i}]]
> f[s]
> {2, 3, 4}
>
> f[s]
> {2, 3}
>
> Andrzej Kozlowski
> Oxford, UK
>
>
>
> On 9 Jan 2007, at 12:49, zac wrote:
>
>> Dear Group,
>>
>> I'm in need of a function, which is called with one argument, a list.
>> The function is to chose one element of the list randomly, AND modify
>> the original list by removing the chosen element from it. My
>> problem is
>> that I cannot modify the global variable from inside the function. It
>> is not a solution to return with a list such as:
>> Return[{chosen_element, modified_local_list}], and than make an
>> assignment outside the function.
>> I'm thinking on some call-by-reference method, but as I've learned so
>> far, there is no user-friendly way to do this, just some workarounds
>> (which I don't know). Any suggestions?
>>
>> Istvan
>>
>> example code below:
>>
>> RandomChoseElem[list_List] := Module[
>>       {pos, elem},
>>       pos = Random[Integer, {1, Length[list]}];
>>       elem = list[[pos]];
>>       (* This is to be solved inside : *)
>>       (* global`list = Drop[global`list, {pos}]; *)
>>       Return[elem]
>>       ];
>>
>> set = {1, 2, 3, 4};
>>
>> RandomChoseElem[set]
>>

```

• Prev by Date: Re: help
• Next by Date: Re: NDSolve with a constraint : how ?
• Previous by thread: Re: Call-by-reference from inside a function
• Next by thread: Re: Call-by-reference from inside a function