Re:FlatStrings
- To: mathgroup <mathgroup at yoda.physics.unc.edu>
- Subject: Re:FlatStrings
- From: HAY at leicester.ac.uk
- Date: Mon, 31 MAY 93 20:05:51 BST
Here are two other, seemingly quicker, approaches (1) is automatic but gives FlatStrings the attribute, HoldAll. Can this be avoided? (2) is not automatic, but it is very simple. I should be interested to hear how they perform on Roberto Sierra's tests. (1) In[5]:= ClearAll[FlatString]; Attributes[FlatString] = {HoldAll}; FlatString[s___ ] := Block[{FlatString, temp}, FlatString[StringJoin@@Flatten[FlatString[temp]]]/; Length[{temp=s}]=!=1||Head[temp] =!=String ] The attribute, HoldAll, prevents expensive evaluation on the right hand side. Block temporarily suppresses the rules and the attribute HoldAll of FlatString and allows almost all the work to be done by single applications of Flatten and StringJoin. The condition used alows us also to deal with expressions like FlatString[s_], FlatString[], which are unevaluated by Tyler Perkin's code. TESTS In[8]:= FlatString[FlatString["a","b"],FlatString["c"]] Out[8]= FlatString[abc] In[9]:= FlatString[FlatString["a","b"]] Out[9]= FlatString[ab] In[10]:= fs := FlatString[FlatString["a","b"],FlatString["c"]]; FlatString[fs] Out[11]= FlatString[abc] In[12]:= FlatString[] Out[12]= FlatString[] (2) In[13]:= ClearAll[FlatString]; CanonicalFS[fs_] := FlatString[StringJoin@@Flatten[fs]] (*you might give CanonicalFS the attribute HoldAll*) TESTS In[16]:= CanonicalFS[FlatString[FlatString["a","b"],FlatString["c"]]] Out[16]= FlatString[abc] In[17]:= CanonicalFS[FlatString[FlatString["a","b"]]] Out[17]= FlatString[ab] In[18]:= fs := FlatString[FlatString["a","b"],FlatString["c"]] CanonicalFS[FlatString[fs]] Out[19]= FlatString[abc] In[20]:= CanonicalFS[FlatString[]] Out[20]= FlatString[] Allan Hayes hay at leicester.ac.uk