MathGroup Archive 2009

[Date Index] [Thread Index] [Author Index]

Search the Archive

StringJoin with ToString

  • To: mathgroup at smc.vnet.net
  • Subject: [mg98291] StringJoin with ToString
  • From: replicatorzed at gmail.com
  • Date: Sun, 5 Apr 2009 06:36:23 -0400 (EDT)

It is quite interesting why StringJoin does not apply ToString to
those arguments which are non-string. I've overridden the built-in
StringJoin, to save a few unnecessary ToStrings by the standard method
(the context specifications are necessary for packaging):

Unprotect[System`StringJoin];
$UseNewStringJoin = True;
System`StringJoin[expr___] :=
  Block[{$UseNewStringJoin = False},
    StringJoin@(ToString /@ {expr})] /; TrueQ[$UseNewStringJoin];
Protect[$UseNewStringJoin];
Protect[System`StringJoin];

This seems to work (after loading the package) for any cases, e.g.:

In[2]:= StringJoin[1, 2, 3]

Out[2]= "123"

In[3]:= 4 <> 5 <> 6

Out[3]= "456"

but has a strange effect on messages:

In[5]:= Append[dummy, 2]

During evaluation of In[5]:= Append::normal: {Nonatomic expression
expected at position , {1},  in , {Append[dummy,2]}, .} >>

Out[5]= Append[dummy, 2]

that is: the message strings are displayed in a non-joined list
format.
The code below shows an other modified StringJoin, that gives the
exact same results (after initiating a fresh kernel):

Unprotect[System`StringJoin];
       System`StringJoin[expr___]:=Module[{str=""},
       Scan[(Print[#]; str=StringInsert[str,ToString[#],-1])&,{expr}];
       str
];
Protect[System`StringJoin];

Now I've inserted a Print[#]; inside the function to see what's
happening. This reveals some internal calculation that is done during
the evaluation of the erroneous call of Append[dummy, 2], which I
don't really understand (did not copy here for size constraints).
Apart from this strange sideeffect on messages (which seems to be
harmless), both functions work as expected. Does anyone have any idea
what is the exact cause of this behaviour and how to overcome it?

Thanks

Istvan Zachar




  • Prev by Date: Re: Can't figure out how to export Mathematica into Word
  • Next by Date: Re: Can't figure out how to export
  • Previous by thread: Re: StringJoin with ToString
  • Next by thread: Re: StringJoin with ToString