I am trying to define a function that takes any two strings (possibly predefined as variables, functions, etc.) and join them in one string (which can also be predefined and will keep its definition if so). For example, join[f,x]
will output fx
and join[myfun,ux]
will output mfunux
. I have tried to use string functions but the inputs need to be quoted. Any suggestions are appreciated.
$\begingroup$
$\endgroup$
$\begingroup$
$\endgroup$
The basic process is to turn the symbols into strings, join them together and then make a symbol again. However, if one of the symbols has a definition this won't work if you don't hold the evaluation of the symbols properly. The following function should work even for symbols that have definitions:
SetAttributes[symbolNameJoin, HoldAll];
symbolNameJoin[symbols__Symbol] := Symbol @ Apply[
StringJoin,
Map[
Function[s, ToString[Unevaluated[s]], HoldFirst],
Hold[symbols]
]
];
Example of use:
x = 1;
symbolNameJoin[x, y, z]
xyz
$\begingroup$
$\endgroup$
Here is a laziyness driven alternative:
SetAttributes[join, HoldAll];
join[sym__Symbol]:= Symbol @ ToString @ HoldForm @ Row @ {sym};
x= 15;
join[x,y,z]
xyz
Symbol
instead ofToExpression
might be a bit safer towards preventing evaluation of unwanted code. $\endgroup$ – Henrik Schumacher Apr 18 '19 at 13:50