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__]
?
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.
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
*)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With