0
|
3196 Views
|
2 Replies
|
2 Total Likes
View groups...
Share
GROUPS:

# Reverse Fold?

Posted 9 years ago
 Is there a functional way to produce the following output In[1]:= X[List, d, {o,l,h,a,i,n,e}] Out[1]= {d,{o,{l,{h,{a,{i,{n,{e}}}}}}}}  the other way around Fold is at hand In[5]:= Fold[List, {First[#]}, Rest[#]] &[{d, o, l, h, a, i, n, e}] Out[5]= {{{{{{{{d}, o}, l}, h}, a}, i}, n}, e} 
2 Replies
Sort By:
Posted 9 years ago
 Fold[{#2, #1} &, {First[#]}, Rest[#]] &[ Reverse@{d, o, l, h, a, i, n, e}] (* Out[14]= {d, {o, {l, {h, {a, {i, {n, {e}}}}}}}} *) (You didn't request elegance.)
Posted 9 years ago
 (You didn't request elegance.) Because I cannot deliver it, too. Nevertheless In[55]:= Reverse[Fold[List, {First[#]}, Rest[#]]&[Reverse[{d, o, l, h, a, i, n, e}]], Range[7]] Out[55]= {d, {o, {l, {h, {a, {i, {n, {e}}}}}}}} here one has to specify how long the argument was; so let's do In[56]:= Reverse[#, Range[Length[Flatten[#]]-1]]&[Fold[List, {First[#]}, Rest[#]]&[Reverse[{d, o, l, h, a, i, n, e}]]] Out[56]= {d, {o, {l, {h, {a, {i, {n, {e}}}}}}}} Stunning, that Reverse finds its way through the expression.