Message Boards Message Boards

0
|
2961 Views
|
8 Replies
|
5 Total Likes
View groups...
Share
Share this post:

[?] Print symbol names with Map?

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
8 Replies

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

Thank you. This works too!

POSTED BY: Fabrice Jossinet

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

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

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

Which also blocks us from getting a correct Lenght.

POSTED BY: Kuba Podkalicki

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

Thank you, this works fine!

POSTED BY: Fabrice Jossinet
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