Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

List to Expression

3 views
Skip to first unread message

Spell

unread,
Dec 31, 2009, 3:17:11 AM12/31/09
to
Hellp,

I am having trouble converting a list into an "expression". For example suppose I have the following list expression.
l = {a, {b, {c, d}}}

When I evaluate the FullForm version, I get an output with List as the Head.
List[a,List[b,List[c,d]]]

But, I would like the following output instead: a[b[c,d]], wondering how this would be accomplised.

PS:
Essentially, I have a FunctionSet with various functions in it. And would like to generate a tree of functions, from the FunctionSet. So, say I have functions from a to d in the set. Then, I can generate something like: d[a[b], c[d[a[b]]].

Thank you.

DrMajorBob

unread,
Jan 1, 2010, 5:32:20 AM1/1/10
to
Close, but no cigar:

{a, {b, {c, d}}} /. List -> Compose

a[b[c[d]]]

ditto:

expr = {a, {b, {c, d}}};
k = Depth@expr;
Replace[expr, List -> Compose, {0, k - 2}, Heads -> True]

Perfect:

expr //. {{a_, b_List} :> a[b], List -> Sequence}

a[b[c, d]]

Bobby


--
DrMaj...@yahoo.com

Adriano Pascoletti

unread,
Jan 1, 2010, 5:34:09 AM1/1/10
to
A solution using ReplaceAll (/.):


In[1]:= l = {a, {b, {c, d}}}; l /. {x_, y_} :> x[y]
% /. {x_, y_} :> x[y]
% /. List -> Sequence
Out[1]= a[{b, {c, d}}]
Out[2]= a[b[{c, d}]]
Out[3]= a[b[c, d]]


In[4]:= l /. {x_, y_} :> x[y] /. {x_, y_} :> x[y] /. List -> Sequence
Out[4]= a[b[c, d]]


Adriano Pascoletti

2009/12/31 Spell <l_sh...@hotmail.com>

dh

unread,
Jan 1, 2010, 5:34:53 AM1/1/10
to
Hi,
you may e.g.use Fold to achieve this:

ll = Reverse@Flatten@l;
Fold[#2[#1] &, First[ll], Rest[ll]]

Daniel

0 new messages