1
$\begingroup$

Abstract: I use a pattern so often that I needed to make a function for constructing it. A function getName[...] for extracting name of variable and value only works when defined globally but does not work if called from another function or even if defined from within a function.

Question: Can this be fixed? If possible the makeRow1[...] is my preferred type of solution.

About the Code: the code below shows 3 different contexts/uses for defining getNamne[...]. Only the globally defined works.

Clear[var]
var = 123; separator = " \[Rule] ";

(* define function in global scope *)
SetAttributes[getName, HoldFirst];
getName[symbol_] := SymbolName[Unevaluated@symbol];
Row[{getName[var], separator, TraditionalForm[var]}]

(* use from within another function *)
makeRow1[var_, separator_ : " \[Rule]"] := 
 Row[{getName[var], separator, TraditionalForm[var]}]
makeRow1[var]

(* define and use within a function *)
makeRow2[var_, separator_ : " \[Rule]"] := Block[{getName},
   SetAttributes[getName, HoldFirst];
   getName[symbol_] := SymbolName[Unevaluated@symbol];
   Row[{getName[var], separator, TraditionalForm[var]}]
   ];
makeRow2[var]
$\endgroup$
2
$\begingroup$

The outer function needs to hold also:

SetAttributes[{makeRow1, makeRow2}, HoldFirst]

test = 1;

makeRow1[test, " : "]
makeRow2[test, " ~ "]
test : 1
test ~ 1
$\endgroup$

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.