2

I am writing a debug function, which prints a variable name, and its value. I call this debug function with a list of variables from anywhere in the program. So the idea is for it to work like this:

debug[var_List] := Module[{values = ReleaseHold[var], i},

  For[i = 1, i <= Length[values], i++,
   Print[var[[i]], " = ", values[[i]]]
   ]
  ];

Now I use the above, like this

x = 3; y = 5;
debug[{HoldForm[x], HoldForm[y]}]

and I see in the console the following

 x = 3
 y = 5

But I have a large program and long list of variables at different places I want to debug. And I do not want to type HoldForm to each variable to make up the list to call the debug[] function. Much easier to Map it if possible. Less typing each time. But this does not work:

 debug[ Map[HoldForm,{x,y}]]

The reason is that {x,y} was evaluated before HoldForm got hold of it. So I end up with a list that has the values in it, like this:

 3 = 3
 5 = 5

I could not find a way to Map HoldForm without the list being evaluated.

The best I could find is this:

debug[HoldForm[Defer[{x, y}]]]

which gives the following output from the above debug[] function:

{x,y} = {3,5}

Since Defer[{x, y}] has length 1, and it is just one thing, I could not break it up to make a 2 column list like in the above example.

It will be better if I can get an output of the form

 x = 3
 y = 5

easier to match the variable with its value since I have many variables.

question is: Any one knows of a programming trick to convert HoldForm[{x,y}] to {HoldForm[x],HoldForm[y]}

thanks

Nasser
  • 12,849
  • 6
  • 52
  • 104
  • 2
    For printing out "debug" values, see: [Printing symbol name and value in Mathematica](http://stackoverflow.com/q/7985052/211232) – WReach Dec 23 '11 at 14:06

3 Answers3

5

Just use Thread:

Thread[HoldForm[{x, y}]]

alternatively,

Map[HoldForm, Unevaluated[{x, y}]]
Leonid Shifrin
  • 22,449
  • 4
  • 68
  • 100
1

Here is a longer alternative demonstrating use of Hold, found in Roman Maeder's Programming In Mathematica (3rd ed.), page 137:

e1 = Hold[{x, y}];
e2 = MapAt[Hold, e1, {1, 0}];
e3 = Map[HoldForm, e2, {2}];
e4 = MapAt[ReleaseHold, First[e3], {0}];
debug[e4]

x=3

y=5

Chris Degnen
  • 8,443
  • 2
  • 23
  • 40
1

I did a PrintIt function using attributes that does what you want. I posted it here https://stackoverflow.com/a/8270643/884752, I repeat the code:

SetAttributes[System`ShowIt, HoldAll];
System`ShowIt[code__] := System`ShowIt[{code}];
System`ShowIt[code_] :=
   With[{y = code},
      Print[Defer[code = y]];
      y
   ]; 

SetAttributes[System`PrintIt, {HoldAll,Listable}];
System`PrintIt[expr__]:=System`PrintIt[{expr}];
System`PrintIt[expr_] := System`ShowIt[expr];
Community
  • 1
  • 1
faysou
  • 1,142
  • 11
  • 25