Re: Insulating data from code
- To: mathgroup at smc.vnet.net
- Subject: [mg66532] Re: Insulating data from code
- From: Jean-Marc Gulliet <jeanmarc.gulliet at gmail.com>
- Date: Fri, 19 May 2006 03:39:31 -0400 (EDT)
- Organization: The Open University, Milton Keynes, UK
- References: <e4ekai$9av$1@smc.vnet.net>
- Sender: owner-wri-mathgroup at wolfram.com
Ray Koopman wrote:
>>From time to time I've wanted to partition the first level of one
> list, say A, the same way that another list, say B, is partitioned.
> One way to do this is
>
> copyPartition[A_List, B_List] /; Length@A >= Length@Flatten@B :=
> Module[{i = 0}, Map[A[[++i]]&,B,{-1}]]
>
> But all the methods I've thought of have a pointer that functions
> something like i in the above code. I'd like to eliminate the pointer,
> because in the unlikely event that A contains an unevaluated symbol
> that is the same as the name of the pointer with $ appended -- e.g.,
> i$, if the pointer is i -- then in the returned list that symbol will
> have a numeric value assigned to it. Unique[i] doesn't help. The
> only solution I see is the probabilistic one of giving the pointer a
> strange (random?) name that hopefully would be very unlikely to show
> up as data. But that would be giving up. Does anyone have any ideas?
>
Hi Ray,
Please find hereunder a function that solve the problem of conflicting
local name in the lists.
In[1]:=
copyPartition2[A_List, B_List] /;
Length[A] >= Length[Flatten[B]] :=
Module[{start, end},
start = FoldList[Plus, 1, Length /@ B];
end = start - 1; start = Most[start];
end = Rest[end];
((A[[#1]] & ) /@ Range[First[#1], Last[#1]] & ) /@
Transpose[{start, end}]]
In[2]:=
listA = {1, 2, 3, 4, 5, 6, 7, i$25, i$26, i$27};
listB = {{a, b}, {2, 6, 1.4, 5/3}, {i}, {a, b, c}};
In[4]:=
copyPartition2[listA, listB]
Out[4]=
{{1, 2}, {3, 4, 5, 6}, {7}, {i$25, i$26, i$27}}
Below, you will find some details about how the function works:
In[5]:=
start = FoldList[Plus, 1, Length /@ listB]
Out[5]=
{1, 3, 7, 8, 11}
In[6]:=
end = start - 1
Out[6]=
{0, 2, 6, 7, 10}
In[7]:=
start = Most[start]
Out[7]=
{1, 3, 7, 8}
In[8]:=
end = Rest[end]
Out[8]=
{2, 6, 7, 10}
In[9]:=
Transpose[{start, end}]
Out[9]=
{{1, 2}, {3, 6}, {7, 7}, {8, 10}}
In[10]:=
(Range[First[#1], Last[#1]] & ) /@
Transpose[{start, end}]
Out[10]=
{{1, 2}, {3, 4, 5, 6}, {7}, {8, 9, 10}}
In[11]:=
((listA[[#1]] & ) /@ Range[First[#1], Last[#1]] & ) /@
Transpose[{start, end}]
Out[11]=
{{1, 2}, {3, 4, 5, 6}, {7}, {i$25, i$26, i$27}}
Best regards,
Jean-Marc