fjossinet
(Fabrice Jossinet)
December 14, 2017, 4:32pm
1
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
kubapod
(Kuba Podkalicki)
December 14, 2017, 11:56pm
2
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}]
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}];
kubapod
(Kuba Podkalicki)
December 15, 2017, 7:23am
4
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]]
kubapod
(Kuba Podkalicki)
December 15, 2017, 10:25am
6
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?
fjossinet
(Fabrice Jossinet)
December 20, 2017, 8:43pm
8
Thank you, this works fine!
fjossinet
(Fabrice Jossinet)
December 20, 2017, 8:45pm
9
Thank you. This works too!