Re: Flatten alternative
- To: mathgroup at smc.vnet.net
- Subject: [mg105498] Re: [mg105469] Flatten alternative
- From: Leonid Shifrin <lshifr at gmail.com>
- Date: Sat, 5 Dec 2009 05:33:54 -0500 (EST)
- References: <200912040931.EAA06957@smc.vnet.net>
Hi, How about this: Clear[myFlatten]; myFlatten[x_List] := x //. y_ :> Replace[y, {a___, {b___}, c___} :> {a, b, c}, {0}] My first attempt by the way was a simpler one: Clear[myFlattenNaive] myFlattenNaive[x_List] := x //. {a___, {b___}, c___} :> {a, b, c}; This looks ok, but fails in the following case, for example: In[1]:= {a,b,{c,{d,{e,f,g[h,{i,j,{k}}]}}}}//myFlattenNaive Out[1]= {a,b,c,d,e,f,g[h,{i,j,k}]} The wrong thing is that it flattens lists also inside ofther heads, and this is not what Flatten does. The more complex version does not do it: In[2]:= {a,b,{c,{d,{e,f,g[h,{i,j,{k}}]}}}}//myFlatten Out[2]= {a,b,c,d,e,f,g[h,{i,j,{k}}]} The added advantage of the myFlatten solution is that it is easy to add to it a level specification as an optional parameter to make myFlatten flatten on a specific level, if this is needed. Needless to say, for deeply nested / complex lists with many sublists on the same level, myFlattenwill be grossly inefficient. Regards, Leonid On Fri, Dec 4, 2009 at 12:31 PM, Jezzybear <jezzybear19 at hotmail.co.uk>wrote: > I am trying to create a function myflat[list] to mimic the behavior of > Mathematica's Flatten[] > function.Example: > In[1]:= myflat[{{{a}}, {b, c}, {d}}] > Out[1]= {a, b, c, d} > In[2]:= myflat[{{}, 1, {{2}}}] > Out[2]= {1, 2} > However in writing this function I want to use only Mathematica's > pattern matching features, the functions > First[], Rest[], Prepend[], ListQ[]. I am trying to do this using some > subfunctions like creating one called myjoin > > >
- References:
- Flatten alternative
- From: Jezzybear <jezzybear19@hotmail.co.uk>
- Flatten alternative