MathGroup Archive 1999

[Date Index] [Thread Index] [Author Index]

Search the Archive

Re: Caution with Block vs Module

  • To: mathgroup at smc.vnet.net
  • Subject: [mg16481] Re: Caution with Block vs Module
  • From: "Allan Hayes" <hay at haystack.demon.co.uk>
  • Date: Tue, 16 Mar 1999 03:59:39 -0500
  • References: <7cd485$o0s@smc.vnet.net>
  • Sender: owner-wri-mathgroup at wolfram.com

Arnold Gregory Civ AFRL/SNAT wrote in message <7cd485$o0s at smc.vnet.net>...
>Hello all:
>
>I just "discovered" a nuance of Block which I did not anticipate so I
>thought I would share it with all of you.
>
>I started using Block as the head of all my functions after reading the
>message a few weeks ago on Block vs. Module.  I thought I understood the
>differences, but the following example took me a long while to track down
>:(
>
>test[eq_]:=Block[{x},x=eq; Return[1]];
>
>test[c*x]
>
>This gives a RecursionLimit.  This occurs because only the value of x is
>blocked.  Therefore test effectively says "x=c*x", which if you try it
>directly will also give you a RecursionLimit.  Based on this aspect of
>Block, I think Module is the most appropriate method (in general) to use
for
>functions!
>
>Greg
>_________________________________________________________
>D. Gregory Arnold, Ph.D.
>Bldg 620  AFRL/SNAT          garnold at mbvlab.wpafb.af.mil
>2241 AVIONICS CIR            Voice:  (937) 255-1115 x4388
>WPAFB OH 45433-7321            FAX:  (937) 656-4414
>_________________________________________________________
>
>

Greg,


I've teased out a variant of your example a bit below

After
test[eq_]:=Block[{x},x=eq];

test[c x] evaluates by the steps:
Block[{x}, x = c x] ,
Block[{x}, c^254*Hold[c*x]] (x = c x evaluated causing recursion)
c^254*Hold[c*x]
(all that Block does is cancel the assignment to x at the end of the Block
evaluation)


After
test2[eq_]:=Module[{x},x=eq];

test2[c*x] evaluates by the steps:
Module[{x$},x$= eq] (x renamed by scoping since eq is the target for eq_ );
Module[{x$},x$ = c x]  (c x is passed to eqn)
Module[{x$n},x$n= c x] (x$ renamed x$n, n is $ModuleNumber)
Module[{x$n},c x] ( x$n= c x evaluated)
c x

We can, improperly, get recursion with test2[c x$]

Allan

---------------------
Allan Hayes
Mathematica Training and Consulting
Leicester UK
www.haystack.demon.co.uk
hay at haystack.demon.co.uk
Voice: +44 (0)116 271 4198
Fax: +44 (0)870 164 0565






  • Prev by Date: Re: mathematica symbols all wrong
  • Next by Date: Re: Abs Symbol
  • Previous by thread: Caution with Block vs Module
  • Next by thread: Re: Caution with Block vs Module