2

I am trying to extract variable names from a list of transformation rules mapping = {var1 -> 'val1', var2 -> 'val2' }. Variables var1 and var2 are already defined in my notebook:

var1 = 'init-val1'; var2 = 'init-val2';

When I try to evaluate Extract[mapping, {1,1}, HoldForm], I get 'init-val1', instead of var1.

What am I doing wrong? Why is var1 getting evaluated despite the explicit HoldForm wrapper? How can I fix the problem?

Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371
verse
  • 1,287
  • 6
  • 18
  • 1
    Check your mapping... the evaluation has already happened when you assigned it to mapping, so the HoldForm is useless. If you explained the intent behind what you're trying to do, then perhaps we can provide a solution that doesn't involve playing catch up with the evaluator. – rm -rf Feb 16 '14 at 21:30
  • @rm-rf, when I evaluate Definition[mapping] I still get {var1 -> 'val1', var2 -> 'val2' }. So in the definition I don't get the substitution of var1 for 'init-val1'. – verse Feb 16 '14 at 21:32
  • var1 = "init-val1"; mapping = {var1 -> "val1", var2 -> "val2"}; Definition[mapping] gives mapping = {"init-val1" -> "val1", var2 -> "val2"}as expected – Dr. belisarius Feb 16 '14 at 21:38
  • @belisarius If you do it the other way round, Definition will give you what the OP said. This is different, because in your case, clearing var1 has no effect on mapping but it does in this one. – rm -rf Feb 16 '14 at 22:01
  • @rm-rf So what does "Variables var1 and var2 are already defined in my notebook:" mean? – Dr. belisarius Feb 16 '14 at 22:07
  • @belisarius The question isn't clear... it isn't apparent whether mapping is defined before or after. Your interpretation is certainly valid given what OP wrote, but if that were the case, then they won't get the output above. That's why I asked OP to explain what they want to do. – rm -rf Feb 16 '14 at 22:13
  • @rm-rf Ok, let's wait for some clarification – Dr. belisarius Feb 16 '14 at 22:31
  • @belisarius, @rm-rf, thanks for the explanation. As soon as var1 and var2 were defined, mappings evaluation used their values instead of name. I had to redefine mappings using HoldForm. – verse Feb 16 '14 at 23:15

1 Answers1

2

This kind of problem is the reason I sought and found a solution to:

Here is an example of how the step function defined in my answer there is used:

var1 = "init-val1"; var2 = "init-val2";

mapping := {var1 -> "val1", var2 -> "val2"}   (* note use of := *)

step[mapping][[{1}, 1, 1]]

% // InputForm
var1

HoldForm[var1]

The return is var1 wrapped in HoldForm. This is because step[mapping] returns:

HoldForm[{var1 -> "val1", var2 -> "val2"}]

And the use of {1} in Part preserves the head; see:

Recommended reading:

Mr.Wizard
  • 271,378
  • 34
  • 587
  • 1,371