1
$\begingroup$

Abstract: I have viewed other solutions on StackExchange but none actually address using a fully self-contained function to return name and value of a variable. The only function that works requires using SetAttributes[...] outside the function before using it: Display variable name instead of value

Goal: to create a completely self-contained function Block[...] or Module[...] that returns variable name and value without requiring using an outside function such as SetAttributes[...].

About the Code: Below is the code for four different attempts. The top two are globally scoped and work fine. Bottom two are written into a function block but do not work. The output is decorated with strings to give you an idea of how I intend to use it.

varname=123;

(* this works *)
Row[{"Global Scope Defer: ","the name is ",Defer@varname," and value is -> ",varname}]

(*this works *)
SetAttributes[ShowName,HoldAll];
ShowName[name_]:=Row[{"Global Scope SetAttributes HoldForm: ","the name is ",HoldForm@name," and value is -> ",ReleaseHold@name}];
ShowName[varname]

(* this doesn't work *)
showDeferFunction[var_]:=Block[{pre,arrow},
pre="the name is ";
arrow=" and value is -> ";
Row[{"Functional Scoping Defer: ",pre,Defer@var,arrow,var}]
];
showDeferFunction[varname]

(* this doesn't work either *)
showHoldFormFunction[var_]:=Block[{pre,arrow},
pre="the name is ";
arrow=" and value is -> ";
SetAttributes[ShowName,HoldAll];
ShowName[name_]:=Row[{"Functional Scoping SetAttributes HoldForm: "pre,HoldForm@name,arrow,ReleaseHold@name}];
ShowName[var]
];
showHoldFormFunction[varname]

The Output:

Global Scope Defer: the name is varname and value is -> 123
Global Scope SetAttributes HoldForm: the name is varname and value is -> 123
Functional Scoping Defer: the name is 123 and value is -> 123
Functional Scoping SetAttributes HoldForm: the name is 123 and value is -> 123
$\endgroup$
  • $\begingroup$ Something like xxx = 1; Function[Null, Row[{Defer[#1], " = ", #1}], {HoldAll}][xxx]? $\endgroup$ – J. M.'s technical difficulties May 23 at 7:13
  • $\begingroup$ @J.M. thank you that is close but I am looking for a named function that would look something like below (example doesn't work) so i could re-use it without having to copy the function body each time: fn[var_] := Function[Null, Row[{Defer[#1], " = ", #1}], {HoldAll}][var]; $\endgroup$ – Jules Manson May 23 at 7:24
  • 1
    $\begingroup$ You don't need var; fn = Function[(* stuff *)] suffices. $\endgroup$ – J. M.'s technical difficulties May 23 at 9:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.