2
$\begingroup$

I'm trying to work with some vectors and have run into a strange problem. An obvious way to define a difference of two vectors would be

dif[x_,y_] := x-y

I thought an equivalent way of doing this would be

dif[x_,y_] := Table[x-z,{z,{y}}][[1]]

However, using this second method, there is some strange behaviour. When I evaluate

dif[{x,z},{0,0}]

I get the result

{x,{0,0}}

which is clearly not what I wanted.

If I try evaluating

dif[{x,y},{0,0}]

instead, everything is ok, which leads me to think that the variable z in my definition of dif is treated as non-local. This seems pretty counterintuitive to me, as I was expecting z to act as a dummy variable.

What am I missing?

One solution that works is using Module. This is a bit unsatisfying though, as it seems to me z should be treated as local even without having to explicitly demand this.

$\endgroup$
7
$\begingroup$

Table doesn't scope the variable like that. This allows you to do things like this:

a = x^2;
Table[a, {x, 0, 3}]
(*{0, 1, 4, 9}*)

In your case you would like to scope z, which you can do via:

dif[x_, y_] := Module[{z}, Table[x - z, {z, {y}}][[1]]]

I think the relevant part of the doc is where it states: "Table effectively uses Block to localize values or variables."

So what it's doing is roughly evaluating: Block[{z=y},x-z], which means any z present in x will also get substituted. Though I think it could have been stated more clearly and properbly should have an example under possible issues.

$\endgroup$
  • $\begingroup$ Interesting ... So I should use modules all over the place just to make sure bad things don't happen? $\endgroup$ – Dejan Govc Feb 12 '13 at 12:52
  • $\begingroup$ @DejanGovc The alternative would be that others would have to write quite complicated code substitution schemes everywhere where they did want to have this sort of behavior. It's quite easy for you to just not use table in this type of situation where you could get by perfectly fine with Map. $\endgroup$ – jVincent Feb 12 '13 at 12:55
  • $\begingroup$ Sounds reasonable. Thanks. $\endgroup$ – Dejan Govc Feb 12 '13 at 12:57
  • $\begingroup$ +1! Beyond this specific question, I think you've displayed a model for great answers -- specific code that does the job + an explanation of why it works. I wish I could keep up voting this kind of answer. $\endgroup$ – Jagra Feb 12 '13 at 14:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.