4
$\begingroup$

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.

$\endgroup$
  • 1
    $\begingroup$ Maybe this: <StringJoin[ ToString /@ {A, f}]> $\endgroup$ – amator2357 Apr 18 at 13:40
  • 1
    $\begingroup$ Then you can go back to an executable expression with ToExpression[StringJoin[ToString /@ {B, f}]] $\endgroup$ – bill s Apr 18 at 13:42
  • 3
    $\begingroup$ Since this is a rather weird thing to do, though, I wanted to check why you want to do that. I wonder if there might be another approach to solving the problem you are actually trying to solve that does not require this. $\endgroup$ – MarcoB Apr 18 at 13:44
  • 1
    $\begingroup$ It should be mentioned that Symbol instead of ToExpression might be a bit safer towards preventing evaluation of unwanted code. $\endgroup$ – Henrik Schumacher Apr 18 at 13:50
5
$\begingroup$

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

$\endgroup$
  • $\begingroup$ This works. Thanks! $\endgroup$ – Bran Apr 18 at 13:52
1
$\begingroup$

Here is a laziyness driven alternative:

SetAttributes[join, HoldAll];
join[sym__Symbol]:= Symbol @ ToString @ HoldForm @ Row @ {sym};

x= 15;
join[x,y,z]

xyz

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.