Message Boards Message Boards

0
|
3404 Views
|
2 Replies
|
2 Total Likes
View groups...
Share
Share this post:
GROUPS:

Reverse Fold?

Posted 10 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}
POSTED BY: Udo Krause
2 Replies
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 BY: Daniel Lichtblau

(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.

POSTED BY: Udo Krause
Reply to this discussion
Community posts can be styled and formatted using the Markdown syntax.
Reply Preview
Attachments
Remove
or Discard

Group Abstract Group Abstract