1

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
Jules Manson
  • 2,457
  • 11
  • 19

0 Answers0