0

Why would this function work with a copy of the function variable:

Clear[zero]
zero[list_] := Module[{listCopy = list}, listCopy[[2]] = 0; listCopy]
zero[{1, 2, 3, 4, 5}]
(* {1, 0, 3, 4, 5} *)

but not when using the variable directly?

Clear[zero]
zero[list_] := Module[{}, list[[2]] = 0; list]
zero[{1, 2, 3, 4, 5}]

Mathematica graphics

seismatica
  • 5,101
  • 1
  • 22
  • 33
  • Please see my answer in the marked duplicate. – Mr.Wizard Aug 05 '14 at 04:25
  • Thanks for your answer in the linked Q&A. It helps me understand on why using my function directly with the list will not work as the value for list will be directly plugged into the RHS of the equation. However, when using listCopy, wouldn't the value of listCopy be plugged in as well? (elaboration: Clear[zero]; zero[list_] := Module[{listCopy = list}, Print[listCopy]; listCopy[[2]] = 0; listCopy]; zero[{1, 2, 3, 4, 5}]). Does Set belong to a class of function (like AppendTo in your answer) that only takes symbol, which may or may not be associated with a value? – seismatica Aug 05 '14 at 04:34
  • 1
    In answer to your last question, basically, yes. Set has the HoldFirst attribute which keeps listCopy[[2]] from evaluating, and Set recognizes this as a special expression and perform the in-place modification. There is controlled evaluation of the first argument of Set which allows patterns to expand etc., but it doesn't relate to your use here. If you wish to know more about that let me know and I'll find relevant material. – Mr.Wizard Aug 05 '14 at 04:57

1 Answers1

1

Because the latter is equivalent to

{1,2,3,4,5}[[2]] = 0

which is invalid. The former stays as

listCopy[[2]] = 0

You can't change (i.e. assign to) parts of a literal like this. You can change (i.e. assign to) a variable.

Generally,

f[x_] := x[[2]]

will substitute the value of x directly. So will With[{x=...}, x[[2]] ]. In contrast, Module[{x={1,2,3}}, x[[2]] ] assigns a value to x, but does not directly replace x with {1,2,3} in the body of the Module.

Szabolcs
  • 234,956
  • 30
  • 623
  • 1,263