Re: There must be a better way!
- To: mathgroup at smc.vnet.net
- Subject: [mg2349] Re: [mg2322] There must be a better way!
- From: gaylord at uiuc.edu (richard j. gaylord)
- Date: Fri, 27 Oct 1995 01:48:28 -0400
- Organization: university of illinois
> > From: mathgroup-adm
To: mathgroup at smc.vnet.net
> > To: mathgroup
> > Subject: [mg2322] There must be a better way!
> > Date: Tuesday, October 24, 1995 2:14AM
> >
> >
> > Hi. I'm trying to write a function that partitions a list into
> > segments of length given by another length. eg.
> > Given l1 = {A,B,C,D,E,F,G,H,I,J}
> > and l2 = {2,3,4,1}
> > I want to be able to say
> > In[1] := MyPartition[l1, l2]
> > and get
> > Out[1] = {{A,B}, {C,D,E}, {F,G,H,I}, {J}}
if you want a function to divy up a list into parts, you can use
split1[lis_, parts_] :=
Module[{dog, cat},
dog[y_, z_] := Take[lis,{y, z}];
cat[x_] := Inner[dog, Drop[x, -1] + 1, Rest[x], List];
cat[FoldList[Plus, 0, parts]] ]
or
split2[lis_, parts_] :=
Module[{pig},
pig[x_] := Take[lis, x + {1, 0}];
Map[pig, Partition[FoldList[Plus, 0, parts], 2, 1]] ]
or much neater looking yet, as a one-liner:
split2[lis_, parts_] :=
Map[Take[lis, # + {1, 0}]&, Partition[FoldList[Plus, 0, parts], 2, 1]]
note: these solutions are given in "Introduction to Programming with
Mathematica" by Gaylord, Kamin and Wellin (the 2nd edition of this book
was just published).
-richard-
--
"if you're not programming functionally, then you're programming dysfunctionally"