Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

converting symbols to strings without evaluation

How can I make toStr[list] that takes a list of symbols and returns them as strings? I'd like a=1;toStr[{a}] to give {"a"}

Update 03/02: Leo's recipe works, also to make a version which takes a sequence instead of list I did SetAttribute[toStr2,HoldAll];toStr2[a__]:=toStr[{a}]

like image 537
Yaroslav Bulatov Avatar asked Mar 02 '11 08:03

Yaroslav Bulatov


1 Answers

You can use HoldForm:

a = 1; b = 2;ToString@HoldForm[{a, b}]

This gives {a, b}. To make it into toStr function, you need to set the attributes so that it doesn't evaluate the arguments:

ClearAll[toStr]; SetAttributes[toStr, {HoldAll, Listable}];
toStr[x_] := ToString@HoldForm[x];
a = 1; b = 2; toStr[{a, b}]

Alternatively, you could use Unevaluated; in the above code toStr[x_] := ToString@Unevaluated[x] would work just as well.

like image 184
Leo Alekseyev Avatar answered Oct 15 '22 01:10

Leo Alekseyev