Assigning to function argument -- How to do it & Novice info
- To: mathgroup at smc.vnet.net
- Subject: [mg3591] Assigning to function argument -- How to do it & Novice info
- From: pecora at zoltar.nrl.navy.mil (Lou Pecora)
- Date: Wed, 27 Mar 1996 03:27:18 -0500
- Organization: Naval Research Lab
- Sender: owner-wri-mathgroup at wolfram.com
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.
x=y^3;
f[x]
Will generate the error message:
3
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
message.
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];)
SetAttributes[f,HoldAll];
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
USA
pecora at zoltar.nrl.navy.mil
/* My views are not those of the U.S. Navy.
If you want their views, you have to go to war. */
==== [MESSAGE SEPARATOR] ====