1

The following MWE should give a symbolic function (is this the correct terminology?) f, defined on the entries of some list list. As a test, we also print the output of f of each "basis" element.

list = Table[i, {i, 1, 3}];

For[j = 1, j <= 3, j++,
  f[list[[j]]] := Symbol["c" <> ToString[j]];
  Print[f[j]];
];

The output is of course

c1
c2
c3

However, if we map f to list,

f /@ list

then the output is

{c4,c4,c4}

I don't expect this, and scoping doesn't help either. So my questions are:

  • Why is this happening?

  • How can I resolve this problem?


EDIT:

I found a solution: I simply changed that one line to

f[list[[j]]] := Evaluate[ Symbol["c" <> ToString[j]] ];

But I still want to know why it happened in the first place? Why is mathematica not resolving the variable in the for loop?

Jo Mo
  • 175
  • 5
  • Look at Definition@f and Definition@j, that should answer your question. Also, instead of …:=Evaluate[…], simply use …=…, which automatically evaluates the right hand side when evaluated. – Lukas Lang Jul 25 '18 at 08:35
  • What is lambda[j] in your code? – Alex Trounev Jul 25 '18 at 08:41
  • Oh you are right! := is basically something like "delayed evaluation", right? Totally forgot that. – Jo Mo Jul 25 '18 at 08:41
  • @AlexTrounev: It's f[j], I just forgot to rename it. – Jo Mo Jul 25 '18 at 08:42
  • OK, see list = Table[i, {i, 1, 3}]; f[j_] := Symbol["c" <> ToString[list[[j]]]]; For[j = 1, j <= 3, j++, Print[f[j]];]; out c1 c2 c3; f /@ list out {c1, c2, c3} – Alex Trounev Jul 25 '18 at 08:53
  • Really? That's not what I get. If I just copy your inputs, Alex, I will still get {c4,c4,c4} after Map. Weird – Jo Mo Jul 25 '18 at 08:56
  • 1
    I have marked this question as already has an answer -- please see the banner inserted at the top. The cause and solution are the same. The right-hand-side of a := expression is held. You can in this case merely use Set (shorthand =) instead: f[list[[j]]] = Symbol["c" <> ToString[j]] but also see the linked question for a better understanding. Also reference (633) for why With is useful there. – Mr.Wizard Jul 25 '18 at 09:35

0 Answers0