Message Boards Message Boards

GROUPS:

[✓] Print symbol names with Map?

Posted 11 months ago
689 Views
|
8 Replies
|
5 Total Likes
|

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

8 Replies

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}]

Thank you, this works fine!

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}];

Which also blocks us from getting a correct Lenght.

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]]

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 :)

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?

Thank you. This works too!

Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract