[Date Index]
[Thread Index]
[Author Index]
variable capture issues with Module, Block and pure/defined functions
*To*: mathgroup at smc.vnet.net
*Subject*: [mg83090] variable capture issues with Module, Block and pure/defined functions
*From*: Matthew Fairtlough <matthew at fairtlough.net>
*Date*: Sat, 10 Nov 2007 03:42:46 -0500 (EST)
Apologies for sending this question twice; the first time I attached a
very short notebook containing the examples I discuss below but then I
thought it might be rejected because of the attachment. So here goes again:
Dear folks,
I was under the impression that you could set up a Module or Block
within a function definition and be sure that any variable clashes would
be resolved. This does not seem to be the case. What is stranger, if I
define testWierd[t_]:=Module[{y=0},t===y] and evaluate testWierd[y] I
get False (which is the behaviour I expected and in fact wanted; it
seems logical since y===0 evaluates to False for an undefined symbol y
and the variable y within the module is supposed to be a local variable
which is actually given a value) and yet if I use a pure Function
instead with exactly the same body: Module[{y=0},#===y]&[y] then I get
True. On the other hand, if I use a Block instead of Module in the
definition of testWierd (as in testWierd2 below) or in a pure function
(as in Block[{y=0},#===y]&[y]) then in both cases the supplied variable
y is captured within the Block and the result is True in both cases.
Is this standard behaviour, or do others get different results? It does
seem odd that Module and Block behave differently in this case and pure
functions and defined functions also behave differently even when they
have exactly the same bodies. This behaviour is starkly illustrated in
the example below; the only difference between the two expressions is
that the formal parameter is named in the second case and unnamed in the
first case. It somehow seems reasonable that they should yield the same
results.
In[12]:=
Function[Module[{y=0},#===y]][y]
Function[t,Module[{y=0},t===y]][y]
Out[12]= True
Out[13]= False
In[31]:=
testWierd[t_]:=Module[{y=0},t===y]
testWierd[y]
Module[{y=0},#===y]&[y]
y===0
y=3;
testWierd[y]
Clear[y]
testWierd[y]//Trace
Out[32]= False
Out[33]= True
Out[34]= False
Out[36]= False
Out[38]=
{testWierd[y],Module[{y$=0},y===y$],{y$93=0,0},{{y$93,0},y===0,False},False}
In[111]:= testWierd2[t_]:=Block[{y=0},t===y]
testWierd2[y]
Block[{y=0},#===y]&[y]
y===0
y=3;
testWierd[y]
Clear[y]
Out[112]= True
Out[113]= True
Out[114]= False
Out[116]= False
{$LicenseID, $Version, $ReleaseNumber}
{"L4698-4301", "6.0 for Microsoft Windows (32-bit) (June 19, 2007)",
1}
Prev by Date:
**Re: $UserBaseDirectory**
Next by Date:
**Re: Matrix multiplication speed up**
Previous by thread:
** Editing one's own default StyleSheet?**
Next by thread:
**Mathematica 6.0.0 crashes on OSX 10.4.10**
| |