Mathematica 9 is now available
Services & Resources / Wolfram Forums
-----
 /
MathGroup Archive
1998
*January
*February
*March
*April
*May
*June
*July
*August
*September
*October
*November
*December
*Archive Index
*Ask about this page
*Print this page
*Give us feedback
*Sign up for the Wolfram Insider

MathGroup Archive 1998

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

Search the Archive

Re: How to change the argument of a function?



Stonewall Ballard wrote:
> 
> In article <6brkhm$lqs$3@dragonfly.wolfram.com>,
> seanross@worldnet.att.net wrote:
> 
> > Vilis Nams wrote:
> > >
> > > I want to define a function that in the course of doing something, also
> > > changes the value of its argument, for example: f[x_]:=Module[{},
> > > x=2*x;
> > > x
> > > ]
> > > When I run the function, I get the error: "Set::setraw : Cannot assign
> > > to raw object  ...." Can this be done in some way?
> > >
> > > --------------------
> > > Vilis O. Nams
> > > Dept of Biology, NSAC
> > > Box 550, Truro, NS,  Canada
> > > vnams @ nsac.ns.ca
> > > -------------------
> >
> >
> > If I have an argument I want to change in the course of a functional
> > evaluation, I make a "working" copy at the beginning of the function:
> >
> > f[x_]:=Module[{y},
> >   y=x;
> > > y=2*y;
> > > y
> > > ]
> >
> > I don't think you can change the value of the actual argument inside a
> > function, or if you could that it would be a good idea.  If you made
> > global changes inside a local function, it might make for some
> > interesting bugs that would be very hard to track down. --
> > Remove the _nospam_ in the return address to respond.
> 
> This is a classic programming problem, solved by using "reference" args
> or "call by name". The example used in most cases is swap[x, y], which
> swaps the values of the arguments.
> 
> In Mathematica it can be done like:
> 
>   swap[x_, y_] := Module[{t = x}, x = y; y = t;]
> 
>   SetAttributes[swap, HoldAll]
> 
> then try:
> 
>   foo = 1
> 1
>   bar = 5
> 5
>   swap[foo, bar]
> 
>   foo
> 5
>   bar
> 1
> 
>   - Stoney
> 
> --
> Stonewall Ballard                    StoneSoft, Inc.
> sb.nospam@stonesoft.com    http://www.stonesoft.com/


Or

In[1]:=
$Line=0;

In[1]:=
SetAttributes[swap, HoldAll]
swap[x_, y_] := ({x,y} = {y,x};)

In[3]:=
{foo, bar} = {1,5}

Out[3]=
{1, 5}

In[4]:=
swap[foo,bar]

In[5]:=
{foo,bar}

Out[5]=
{5, 1}


-- 
Allan Hayes
Training and Consulting
Leicester, UK
hay@haystack.demon.co.uk
http://www.haystack.demon.co.uk
voice: +44 (0)116 271 4198
fax: +44 (0)116 271 8642




  • Prev by Date: Re: summations!
  • Next by Date: Drawing intrinsic coordinate graphs
  • Prev by thread: Re: How to change the argument of a function?
  • Next by thread: Re: How to change the argument of a function?