Message Boards Message Boards

[✓] Print symbol names with Map?

GROUPS:

Hi all,

to illustrate my question, I will use this toy example.

I would like to print the symbol names along with the length of the lists they're attached to. Like:

a = Range[1, 5];
b = Range[1, 10];
Print[SymbolName@Unevaluated@a, ": ", Length@a]
Print[SymbolName@Unevaluated@b, ": ", Length@b]

This works fine. But now, I would like to do that with Map:

Print[SymbolName@Unevaluated@#, ": ", Length@#] & /@ {a, b}

This doesn't work. It seems that the mapping evaluates the elements before to apply them to my pure function. Any help would be nice.Thanx,

Fabrice

POSTED BY: Fabrice Jossinet
Answer
4 months ago

Map does not hold so:

Print[SymbolName@Unevaluated@#, ": ", Length@#] & /@  Unevaluated /@ Unevaluated@{a, b}

or, more readable:

Function[
  s
, Print[SymbolName@Unevaluated@s, ": ", Length@s]
, {HoldAll, Listable}
][{a, b}]
POSTED BY: Kuba Podkalicki
Answer
4 months ago

Thank you, this works fine!

POSTED BY: Fabrice Jossinet
Answer
4 months ago

Map does not hold its arguments. You can block the evaluation of a,b using Block:

a = Range[1, 5];
b = Range[1, 10];
Block[{a, b},
  Print[SymbolName@#, ": ", Length@#] & /@ {a, b}];
POSTED BY: Gianluca Gorni
Answer
4 months ago

Which also blocks us from getting a correct Lenght.

POSTED BY: Kuba Podkalicki
Answer
4 months ago

You are right:

a = Range[1, 5];
b = Range[1, 10];
Block[{a, b, Length}, 
 Grid[{SymbolName@#, ": ", Length@#} & /@ {a, b}]]

I just learned that Print finalizes the printout before exiting Block:

x = 1;
Block[{x}, Print[x]]
Block[{Now}, Print[Now]]
POSTED BY: Gianluca Gorni
Answer
4 months ago

Correct, and sorry for being picky but returning a result is not the same what Print does. E.g. In my preferences I have PrintToConsole. But in general the difference is deeper, it is like expr vs. Write[$Output, expr].

Which may not matter anyway if user is fine with your solution :)

POSTED BY: Kuba Podkalicki
Answer
4 months ago

You can Print the output of Block:

a = Range[1, 5];
b = Range[1, 10];
Block[{a, b, Length}, 
   Grid[{SymbolName@#, ": ", Length@#} & /@ {a, b}]] // Print;

Does that show on the console?

POSTED BY: Gianluca Gorni
Answer
4 months ago

Thank you. This works too!

POSTED BY: Fabrice Jossinet
Answer
4 months ago

Group Abstract Group Abstract