a plug for Block, Re: mg[758]
- To: mathgroup at christensen.cybernetics.net
- Subject: [mg823] a plug for Block, Re: mg[758]
- From: Allan Hayes <hay at haystack.demon.co.uk>
- Date: Mon, 24 Apr 1995 02:47:10 -0400
Block[{a,b=c},expr] blocks off any existing definitions for a and
b; defines b = c; evaluates expr; then removes the definition b = c
and unblocks any previous definitions for a and b.
Here is a use for this sort of behaviour:
In mg[758] David Wagner creates
In[1]:=
factorization =
(IntegerPower[2, 2] IntegerPower[3, 2] IntegerPower[5, 3]
IntegerPower[53, 1])
Which, with his formatting for IntegerPower, prints as
Out[1]=
2 2 3 1
2 3 5 53
Then, to evaluate this form to 238500, he defines
In[2]:=
ExpandInteger[x:(a_IntegerPower * b_.)] :=
x /. IntegerPower->Power
ExpandInteger[x_] := x
In[4]:=
ExpandInteger[factorization]
Out[4]=
238500
An alternative to ExpandInteger, which is also faster, is
In[5]:=
ExpandInteger2[expr_]:= Block[{IntegerPower = Power},expr]
This evaluates expr with IntegerPower temporarily set to Power
(which is what we want).
Here are the timings
In[6]:=
Do[ExpandInteger2[factorization],{1000}]//Timing
Out[6]=
{1.88333 Second, Null}
In[7]:=
Do[ExpandInteger[factorization],{1000}]//Timing
Out[7]=
{2.83333 Second, Null}
ExpandInteger2 also gets inside expressions, which ExpandInteger
does not do:
In[8]:=
ExpandInteger[{factorization}]
Out[8]=
2 2 3 1
{2 3 5 53 }
In[9]:=
ExpandInteger2[{factorization}]
Out[9]=
{238500}
Allan Hayes
hay at haystack.demon.co.uk