MathGroup Archive 1996

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

Search the Archive

Assigning to function argument -- How to do it & Novice info

  • To: mathgroup at
  • Subject: [mg3591] Assigning to function argument -- How to do it & Novice info
  • From: pecora at (Lou Pecora)
  • Date: Wed, 27 Mar 1996 03:27:18 -0500
  • Organization: Naval Research Lab
  • Sender: owner-wri-mathgroup at

Here's one that got me (and I'm only a semi-novice).

Suppose you want to have a function that will change the value of an
argument (assign it to something else).  For example,

f[a_] := (a=Sin[33.26];)

If x already has been assigned to something this will _not_ work.  E.g.


Will generate the error message:

Set::write: Tag Power in y  is Protected.

In fact any assignment of x= something will generate an error. If you
really wanted to pass an aleady existing variable to a function and
reassign it a value in the function, this will drive you nuts!  The reason
it happens is because the arguments of a function are evaluated _before_
being passed, so f[x] is evaluated to f[y^3] then the function is called. 
So within it you are trying to assign Power[y,3]=Sin[33.26], which doesn't
make sense and cannot be done because Power is protected, hence the error

So what's the solution?  You need to set the Attributes of f to HoldAll
which means the arguments are _not_ evaluated before being used in the
function.  Then things work fine.  So you would do
f[a_] := (a=Sin[33.26];)

Now f[x] will assign Sin[33.26] to x.

I thought this reminder post was worth it since it could take some (like
me) a long time to figure it out.  Life's too short.  Have fun.

Lou Pecora
code 6341
Naval Research Lab
Washington  DC  20375
pecora at
/* My views are not those of the U.S. Navy. 
   If you want their views, you have to go to war. */


  • Prev by Date: Re: addressing matrix elements
  • Next by Date: ISSAC'96 CALL FOR POSTERS
  • Previous by thread: packages
  • Next by thread: ISSAC'96 CALL FOR POSTERS