3
$\begingroup$

This is a trivial function, just to show that Module does not recognize the list generated by Table.

f1[x_] := Module[Table[out[i], {i, 1, Length[x]}], 42]
f1[{1, 2, 3}]
$\endgroup$
3
  • 3
    $\begingroup$ Only the base variable needs to be specified in the Module. For example, f1[x_] := Module[{out}, Table[out[i] = x[[i]], {i, 1, Length[x]}]; out[1] + 2*out[2] + out[3]^2]; then f1[{1, 2, 3}] evaluates to 14 and neither out nor its indexed values are defined in the global name space. $\endgroup$
    – Bob Hanlon
    Commented Oct 12, 2020 at 23:48
  • 1
    $\begingroup$ What are you trying to accomplish? What is your desired output from this f1? $\endgroup$
    – bill s
    Commented Oct 13, 2020 at 1:43
  • $\begingroup$ ok Bob this is what I need, many thanks $\endgroup$
    – pablo
    Commented Oct 14, 2020 at 11:51

2 Answers 2

4
$\begingroup$

In an even more trivial case. It appears that Module is not willing to recognize such indexed variables as symbols:

f2[x_] := Module[{out[1]}, out[1] = x; out[1]]

f2[5]

Module::lvsym: Local variable specification {out[1]} contains out[1], which is not a symbol or an assignment to a symbol

Module[{out[1]}, out[1] = 5; out[1]]
$\endgroup$
1
  • $\begingroup$ Correct. You can only localize symbols; not arbitrary expressions. $\endgroup$ Commented Oct 13, 2020 at 10:12
3
$\begingroup$

According to the Help, ''Every time a module is evaluated, a new temporary symbol is created'' and ''Block localizes values only; it does not create new symbols''

Clear["`*"]; 
f1[x_] := Block[{out}, Table[out[i], {i, 1, Length[x]}, 42]]
f1[{1, 2, 3}]
$\endgroup$
1
  • $\begingroup$ I do not understand the output of this $\endgroup$
    – pablo
    Commented Oct 14, 2020 at 11:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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