Services & Resources / Wolfram Forums
-----
 /
MathGroup Archive
1992
*January
*February
*March
*April
*May
*June
*July
*August
*September
*October
*November
*December
*Archive Index
*Ask about this page
*Print this page
*Give us feedback
*Sign up for the Wolfram Insider

MathGroup Archive 1992

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

Search the Archive

Re: Flattening

  • To: mathgroup at yoda.physics.unc.edu
  • Subject: Re: Flattening
  • From: Cetin Cetinkaya <cetin%acm4 at yoda.physics.unc.edu>
  • Date: Fri, 3 Apr 1992 13:32:48 -0600

 gaylord at ux1.cso.uiuc.edu writes:



>Subject: elegance vs. 'quick and dirty': a Mathematica expression beauty contest 

>a recent discussion of Flattening dealt with going from

        startlist = {{a,a,a},{a,a},{{b,b},{b,b,b}},{a,a,a,a},{{b,b},{b}}}
>to
        finallist = {{a,a,a},{a,a},{b,b},{b,b,b},{a,a,a,a},{b,b},{b}}


>Three solutions have been proposed:

>#1

>finallist = FixedPoint[
                Replace[#,{A___,List[X___List],B___} :> {A,X,B}]&,
                startlist]

>Let $A be an unused or local symbol

>finallist = Flatten[List @@ (
                      startlist /. List[X___List] :> $A[X] 
                              /. {List->$A,$A->List}
                     )
                   ] /. $A->List

>#2
 
>f[x_List] :=
> Apply[Join,Map[(If[Head[First[#]] === List, #, {#}] &), x]]
 
#>3

>f[{x__}] := Sequence[x] /; Not[ And @@ AtomQ /@ {x} ]
>f[{x__}] := {x}
>f /@ startlist

>==========================

>#2 and #3 have been proposed by their authors as being 'quick and dirty'. I
>don't agree at all with the authors. I rank these expressions in terms of
>'elegance in the order
>#2, #3, #1  



But I think the true winner is number 1 because it is the only one which works!
Let me explain what I mean:


In[14]:= f[x_List] :=
                   Apply[Join,Map[(If[Head[First[#]] === List, #, {#}] &), x]]    
0.  1317.904 KByte

In[15]:= f[{{{{a,b},{c,d}}}}]
0.  1318.38 KByte

Out[15]= {{{a, b}, {c, d}}}   


Thus, number 2 does not work for more general lists. Only "first order" lists
can be handled using it.


In[16]:= f[{x__}] := Sequence[x] /; Not[ And @@ AtomQ /@ {x} ]
0.  1319.276 KByte

In[17]:= f[{x__}] := {x}
0.  1319.988 KByte

In[18]:= f/@{{{{a,b},{c,d}}}}  
0.  1320.492 KByte

Out[18]= {{{a, b}, {c, d}}} 

And this shows that number 3 does not work,either.  However, 

In[20]:= FixedPoint[
               Replace[#,{A___,List[X___List],B___} :> {A,X,B}]&,
              {{{{{{a,b},{c,d}}}}}}]
0.0166667 Second  1322.456 KByte

Out[20]= {{a, b}, {c, d}} 


Therefore, the only working one and the winner is number 1.



ccetinkaya














  • Prev by Date: Re: bug in Splice?
  • Next by Date: Re: Ceiling & Floor
  • Previous by thread: Re: bug in Splice?
  • Next by thread: Re: Flattening