• To: mathgroup at smc.vnet.net
• Subject: [mg5219] Re:[mg5161] Programming: Replace Heads
• From: fransm at win.tue.nl (Frans Martens)
• Date: Fri, 15 Nov 1996 03:22:38 -0500
• Sender: owner-wri-mathgroup at wolfram.com

```Xah Lee posed a programming problem and gave a solution.

Problem:
Given an abritrary expression, how to replace all heads to List?

Solution:
Map[ {(Sequence@@#)}&, (*(* the arbitrary expression *)*), {0,-2}]

I ran in some difficulties. Here is an example:

In[70]:=
Hold[a[b[c[u+2]+3]+4]] /. Thread[{a,b,c,Plus}->List] // ReleaseHold
Out[70]=
{{{{{{u, 2}}, 3}}, 4}}
In[71]:=
Map[ {(Sequence@@#)}&, a[b[c[u+2]+3]+4], {0,-2}]

Out[71]=
{{{{9, 7 + u}}}}

The following function computes first the expression and replaces all

In[74]:=
{1,Infinity}]];

In[78]:=
Out[78]=
{{4, {{3, {{2, u}}}}}}

Mind the difference with %70 !

In[80]:=
Clear[a,b,c,d,e,f,g]
f := ({a,b,c,d,e,g}[[Random[Integer, {1,6}] ]])
Array[ Hold at f, {3,2,3},1, Hold at f]//ReleaseHold
Map[ {(Sequence@@#)}&, %, {0,-2}]
Out[82]=
c[g[g[d[1, 1, 1], e[1, 1, 2], e[1, 1, 3]],

a[d[1, 2, 1], d[1, 2, 2], g[1, 2, 3]]],

e[b[c[2, 1, 1], a[2, 1, 2], e[2, 1, 3]],

e[a[2, 2, 1], c[2, 2, 2], b[2, 2, 3]]],

b[e[c[3, 1, 1], d[3, 1, 2], d[3, 1, 3]],

a[b[3, 2, 1], c[3, 2, 2], d[3, 2, 3]]]]
Out[83]=
{{{{1, 1, 1}, {1, 1, 2}, {1, 1, 3}},

{{1, 2, 1}, {1, 2, 2}, {1, 2, 3}}},

{{{2, 1, 1}, {2, 1, 2}, {2, 1, 3}},

{{2, 2, 1}, {2, 2, 2}, {2, 2, 3}}},

{{{3, 1, 1}, {3, 1, 2}, {3, 1, 3}},

{{3, 2, 1}, {3, 2, 2}, {3, 2, 3}}}}
Out[84]=
{{{{1, 1, 1}, {1, 1, 2}, {1, 1, 3}},

{{1, 2, 1}, {1, 2, 2}, {1, 2, 3}}},

{{{2, 1, 1}, {2, 1, 2}, {2, 1, 3}},

{{2, 2, 1}, {2, 2, 2}, {2, 2, 3}}},

{{{3, 1, 1}, {3, 1, 2}, {3, 1, 3}},

{{3, 2, 1}, {3, 2, 2}, {3, 2, 3}}}}

For the freaks I compared the timings!

In[112]:=
Clear[a,b,c,d,e,f,g]
f := ({a,b,c,d,e,g}[[Random[Integer, {1,6}] ]])
Array[ Hold at f, {4,6,10},1, Hold at f]//ReleaseHold;
Timing[aa = Map[ {(Sequence@@#)}&, %, {0,-2}];]
aa === bb
Out[115]=
{0.15 Second, Null}
Out[116]=
{0.0333333 Second, Null}
Out[117]=
True

In[118]:=
Clear[a,b,c,d,e,f,g]
f := ({a,b,c,d,e,g}[[Random[Integer, {1,6}] ]])
Array[ Hold at f, {8,8,10},1, Hold at f]//ReleaseHold;
Timing[aa = Map[ {(Sequence@@#)}&, %, {0,-2}];]
aa === bb
Out[121]=
{0.366667 Second, Null}
Out[122]=
{0.05 Second, Null}
Out[123]=
True

Frans Martens
Eindhoven
The Netherlands

```

• Prev by Date: mathlink and matrices
• Next by Date: Problem with ReadList[]
• Previous by thread: Re: Programming: Replace Heads
• Next by thread: Re: Programming: Replace Heads