Re: print variable name and its value
- To: mathgroup at smc.vnet.net
- Subject: [mg99984] Re: print variable name and its value
- From: Albert Retey <awnl at gmx-topmail.de>
- Date: Thu, 21 May 2009 00:05:29 -0400 (EDT)
- References: <gv0ius$b8v$1@smc.vnet.net>
Karsten W. wrote:
> Hello,
>
> how can I dump out a variable with its value? The following does not
> work:
>
> myVar1 = 1;
> myVar2 = 2;
> DumpVars[list_List] :=
> MapThread[(Print[#1, ": ", #2]) &, {Map[ToString[#] &,
> Unevaluated[list]], list}];
>
> DumpVar[var_] := Print[ToString[Unevaluated[var]], ":", var];
>
>
> DumpVars[{myVar1, myVar2}]
> DumpVar[myVar1]
>
> Any ideas?
Use attributes. To get ahold of the unevaluated forms within the
function definition you _need_ HoldFirst (or HoldAll). Listable just
makes the code simpler and probably can motivate you to learn more about
how attributes can make your life easier :-)
The following should do what you want:
ClearAll[DumpVar]
SetAttributes[DumpVar, {HoldFirst, Listable}]
DumpVar[s_Symbol] := (Print[HoldForm[s], ": ", s]);
Note that these both do work without further definitions, thanks to the
attribute Listable:
DumpVar[myVar1];
DumpVar[{myVar1, myVar2}];
hth,
albert