Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Printing symbol name and value in Mathematica

I'd like to create a function My`Print[args__] that prints the names of the symbols that I pass it, along with their values. The problem is that before the symbols are passed to My`Print, they're evaluated. So My`Print never gets to see the symbol names.

One solution is to surround every argument that I pass to My`Print with Unevaluated[], but this seems messy. Is there a way of defining a MACRO such that when I type My`Print[args__], the Mathematica Kernel sees My`Print[Unevaluated /@ args__]?

like image 575
rjkaplan Avatar asked Nov 02 '11 17:11

rjkaplan


2 Answers

You need to set the attribute HoldAll on your function, with SetAttribute[my`print].

Here's a possible implementation:

Clear[my`print]
SetAttributes[my`print, HoldAll]
my`print[args__] := 
 Scan[
  Function[x, Print[Unevaluated[x], " = ", x], {HoldAll}], 
  Hold[args]
 ]

I used lowercase names to avoid conflicts with built-ins or functions from packages.

EDIT:

Just to make it explicit: I have two functions here. One will print the value of a single symbol, and is implemented as a Function inside. You can just use this on its own if it's sufficient. The other is the actual my`print function. Note that both need to have the HoldAll attribute.

like image 161
Szabolcs Avatar answered Nov 02 '22 16:11

Szabolcs


ClearAll[My`Print]
SetAttributes[My`Print, HoldAll]
My`Print[args___] := 
 Do[
   Print[
      Extract[Hold[args], i, HoldForm], "=", List[args][[i]]
   ], {i, Length[List[args]]}
 ]

ape = 20;
nut := 20 ape;
mouse = cat + nut;

My`Print[ape, nut, mouse]

(* ==>
ape=20
nut=400
mouse=400+cat
*)
like image 30
Sjoerd C. de Vries Avatar answered Nov 02 '22 16:11

Sjoerd C. de Vries