MathGroup Archive 2007

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

Search the Archive

Re: Call-by-reference from inside a function

  • To: mathgroup at smc.vnet.net
  • Subject: [mg72577] Re: Call-by-reference from inside a function
  • From: Jean-Marc Gulliet <jeanmarc.gulliet at gmail.com>
  • Date: Wed, 10 Jan 2007 02:55:00 -0500 (EST)
  • Organization: The Open University, Milton Keynes, UK
  • References: <eo012n$kp1$1@smc.vnet.net>

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

Setting the attribute HoldFirst to your function will do the trick. For 
a nice, detailed, and clear explanation see Daniel Lichtblau answer to 
the thread "is there really no efficient way to delete an element from a 
list??" (Mathgroup, June 28 2000)

http://groups-beta.google.com/group/comp.soft-sys.math.mathematica/browse_thread/thread/a7762aea066f29c0/8436f232fc060841?lnk=gst&q=call+reference&rnum=8&hl=en#8436f232fc060841

Here is your function (with some minor modification):

In[1]:=
Remove[RandomChoseElem];
SetAttributes[RandomChoseElem, HoldFirst];
RandomChoseElem[list_]:=Module[{pos,elem},
       pos=Random[Integer,{1,Length[list]}];
       elem=list[[pos]];
       list=Drop[list,{pos}];
       elem (* Return is not needed here *)
       ];
set={1,2,3,4};
RandomChoseElem[set]
set

Out[5]=
3

Out[6]=
{1,2,4}

Regards,
Jean-Marc


  • Prev by Date: Re: How to export txt files with variable name &
  • Next by Date: Efficient Computation involving a Hypergeometric function...
  • Previous by thread: Re: Call-by-reference from inside a function
  • Next by thread: Re: Call-by-reference from inside a function