开发者

converting symbols to strings without evaluation

开发者 https://www.devze.com 2023-02-14 02:41 出处:网络
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\"}

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[{开发者_如何学Goa}]


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消