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: [mg72579] Re: [mg72568] Call-by-reference from inside a function
  • From: János <janos.lobb at yale.edu>
  • Date: Wed, 10 Jan 2007 03:03:02 -0500 (EST)
  • References: <200701091249.HAA21706@smc.vnet.net>

On Jan 9, 2007, at 7:49 AM, 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]

In my humble newbie opinion, you either do not need a scoping Module  
there, or if you do, then you can return a two element list where the  
first member is the dropped element and the second one is the  
modified list.

RandomChoseElem[list_List] := Module[
>       {pos, elem, mlist},
>       pos = Random[Integer, {1, Length[list]}];
>       elem = list[[pos]];
>       mlist = Drop[list, {pos}];
>       Return[{elem,mlist}]
>       ];
>

and then the call would look like:

sss=RandomChoseElem[set]

set=Last[sss];
dropped_element=First[sss];

Csóka családnak,

János


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