Search All of the Math Forum:

Views expressed in these public forums are not endorsed by NCTM or The Math Forum.

Notice: We are no longer accepting new posts, but the forums will continue to be readable.

Replies: 0

 Frans Martens Posts: 14 Registered: 12/7/04
Posted: Nov 9, 1996 2:06 AM

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]:=
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@f, {3,2,3},1, Hold@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@f, {4,6,10},1, Hold@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@f, {8,8,10},1, Hold@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