MathGroup Archive 2006

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

Search the Archive

Re: Question on using Table in module

  • To: mathgroup at smc.vnet.net
  • Subject: [mg67930] Re: [mg67894] Question on using Table in module
  • From: Sseziwa Mukasa <mukasa at jeol.com>
  • Date: Thu, 13 Jul 2006 06:53:39 -0400 (EDT)
  • References: <200607120905.FAA22167@smc.vnet.net>
  • Sender: owner-wri-mathgroup at wolfram.com

On Jul 12, 2006, at 5:05 AM, Nag wrote:

> Hello:
>
> Look at the following code fragment.
>
> a = {1, 0}
> b[x_,n_,d_]:=Module[{i},x[[n]]=d];
> b[a,2,40]
>
> ?a
> a = {1, 0}
>
> Executing gives the error message:
> Set::setps: {1, 0} in assignment of part is not a symbol.
>
> I followed the link to the Help browser, but do not understand the
> explanation.
>
> What is happening here? Please help.

Because of the SetDelayed the argument x is bound to a value when the  
right hand side of the expression for b is evaluated.  Internally b[a, 
2,40] is equivalent to b[{1,0},2,40] which  is:

Module[{i},{1,0}[[2]]=40]

It should be obvious why there is an error.  You can confirm this  
transformation by evaluating Trace[b[a,2,40]]

In Computer Science parlance, x is passed by value, so everywhere x  
appears on the right hand of a SetDelayed expression it will have  
whatever value the argument was assigned when the expression is  
evaluated.  Furthermore, with rare exceptions, Mathematica  
expressions cannot alter the value of their arguments, which makes  
sense in a pass by value system.  If you want to alter the value of a  
you need to write an expression which copies a to a temporary  
internal variable, modify that variable, then assign the result back  
to a eg:

b[x_,n_,d_]:=Module[{i=x},i[[n]]=d;i]

a=b[a,2,40]

Regards,

Ssezi


  • Prev by Date: Re: Use color with ListPlot?
  • Next by Date: Gradient and Hessian matrix of cumulative normal ditribution
  • Previous by thread: Question on using Table in module
  • Next by thread: Re: Question on using Table in module